LinuxNotes

第 28 章:Ansible 自动化

zjc 于 2026-01-28 发布

这是《Linux 零基础实战指南》的独立章节版。本章从概念、实操和生产排查三个视角展开,代码块保留了原书可直接运行的版本。 手工操作难以重复、难审计、容易漂移。Ansible 用 YAML 描述期望状态,用 SSH 执行,适合批量巡检、系统配置、发布预检和应急操作。本章覆盖 inventory、playbook、变量、role、vault、常用模块和 CI 集成。

28.1 安装

python3 -m pip install --user ansible
ansible --version

依赖 SSH:

ssh-keygen -t ed25519
ssh-copy-id app@192.0.2.10

28.2 Inventory

inventory/prod.ini

[web]
web01 ansible_host=192.0.2.10
web02 ansible_host=192.0.2.11

[app]
app01 ansible_host=192.0.2.20
app02 ansible_host=192.0.2.21

[prod:children]
web
app

[prod:vars]
ansible_user=deploy
ansible_python_interpreter=/usr/bin/python3

测试:

ansible all -i inventory/prod.ini -m ping
ansible web -i inventory/prod.ini -a 'uptime'

28.3 Playbook

site.yml

- name: Configure web servers
  hosts: web
  become: true
  gather_facts: true

  tasks:
    - name: Install nginx
      ansible.builtin.package:
        name: nginx
        state: present

    - name: Deploy nginx config
      ansible.builtin.template:
        src: templates/nginx.conf.j2
        dest: /etc/nginx/nginx.conf
        owner: root
        group: root
        mode: "0644"
      notify:
        - Reload nginx

  handlers:
    - name: Reload nginx
      ansible.builtin.service:
        name: nginx
        state: reloaded

执行:

ansible-playbook -i inventory/prod.ini site.yml

语法检查:

ansible-playbook --syntax-check -i inventory/prod.ini site.yml

Dry run:

ansible-playbook --check --diff -i inventory/prod.ini site.yml

28.4 常用模块

| 模块 | 用途 | |—|—| | package | 跨发行版装包 | | service | 服务管理 | | systemd | systemd unit | | copy / template | 分发文件 | | file | 文件与目录 | | user / group | 账号 | | ` authorized_key | SSH 公钥 | | lineinfile | 单行配置 | | replace | 正则替换 | | sysctl | 内核参数 | | firewalld | 防火墙 | | stat | 检查文件 | | uri | HTTP 检查 | | command / shell` | 执行命令 |

优先使用幂等模块,shell 应作为最后选择。

28.5 变量

group_vars/web.yml

nginx_worker_processes: auto
nginx_keepalive_timeout: 65
app_env: production

使用:

- name: Show env
  ansible.builtin.debug:
    msg: "env={{ app_env }}, workers={{ nginx_worker_processes }}"

优先级示例:

extra vars
  -> inventory vars
     -> group_vars
        -> role defaults

敏感变量不要写普通 group_vars。

28.6 条件、循环与变更

条件:

- name: Install chrony on Debian
  ansible.builtin.package:
    name: chrony
    state: present
  when: ansible_facts.os_family == 'Debian'

循环:

- name: Create app users
  ansible.builtin.user:
    name: "{{ item.name }}"
    groups: "{{ item.groups }}"
    state: present
  loop:
    - { name: dev01, groups: release }
    - { name: ops01, groups: ops }

变更处理:

- name: Deploy app
  ansible.builtin.copy:
    src: files/app.jar
    dest: /opt/app/app.jar
  notify:
    - Restart app

handler 只有任务变化时才执行。

28.7 Role

结构:

roles/nginx
  |-- defaults/main.yml
  |-- files/
  |-- handlers/main.yml
  |-- meta/main.yml
  |-- tasks/main.yml
  |-- templates/
  +-- vars/main.yml

使用:

- name: Configure web
  hosts: web
  become: true
  roles:
    - role: nginx
      vars:
        nginx_worker_processes: auto

Galaxy 安装:

ansible-galaxy install geerlingguy.nginx

第三方 role 要评审来源、版本和权限,不能只因为流行就使用。

28.8 Vault

创建加密文件:

ansible-vault create group_vars/all/vault.yml

编辑:

ansible-vault edit group_vars/all/vault.yml

执行:

ansible-playbook --ask-vault-pass -i inventory/prod.ini site.yml

更安全的方式是把密钥交由 Secret Manager,Ansible 只保存引用和权限。

28.9 批量巡检

check.yml

- name: Linux health check
  hosts: all
  become: false
  tasks:
    - name: Collect uptime
      ansible.builtin.command: uptime
      changed_when: false
      register: uptime_output

    - name: Collect disk
      ansible.builtin.command: df -hT
      changed_when: false
      register: disk_output

    - name: Show result
      ansible.builtin.debug:
        msg:
          - "{{ inventory_hostname }}: {{ uptime_output.stdout }}"
          - "{{ disk_output.stdout_lines }}"

执行:

ansible-playbook -i inventory/prod.ini check.yml

28.10 CI/CD 集成

流程:

Git MR
  -> syntax check
     -> lint
        -> test env dry-run
           -> approval
              -> prod canary
                 -> full rollout

要求:

  1. inventory 和代码在仓库;
  2. playbook 有 lint;
  3. 高危 playbook 需要人工审批;
  4. 执行记录保留;
  5. 生产与测试环境变量隔离;
  6. 支持回滚;
  7. Ansible 版本固定。

lint:

ansible-lint site.yml

本章小结

Ansible 把主机、变量、任务、角色和密钥组织成可版本化的自动化。生产使用要坚持幂等、dry-run、审批、审计和回滚。它适合系统配置和批量操作,复杂发布编排可交给专业 CI/CD 系统。

思考题

  1. 幂等性为什么重要?
  2. handler 和普通 task 有什么区别?
  3. 什么情况下不应使用 shell 模块?
  4. 如何安全使用 Ansible Vault?
  5. 设计一套生产主机初始化 playbook。