# Ansible 批量执行与 playbook ## 场景 要在几十台 Linux 上统一装包、推配置、重启服务,SSH 一台台敲太慢。 ## 前置条件 - 控制机到目标机 SSH 免密 - 目标机有 python - 目标机清单(分组、地址) ## 配置 ```bash dnf install -y ansible-core # 或 pip install ansible # 清单 cat >/etc/ansible/hosts <<'EOF' [web] 10.0.0.21 10.0.0.22 [db] 10.0.0.31 [all:vars] ansible_user=deploy ansible_ssh_private_key_file=/home/deploy/.ssh/id_ed25519 EOF # 连通性 ansible all -m ping ansible web -m shell -a "uptime" ``` playbook 示例: ```yaml # site.yml - hosts: web become: yes tasks: - name: 装 nginx dnf: name: nginx state: present - name: 推配置 copy: src: files/nginx.conf dest: /etc/nginx/nginx.conf mode: "0644" notify: reload nginx - name: 确保服务启动 service: name: nginx state: started enabled: yes handlers: - name: reload nginx service: name: nginx state: reloaded ``` ```bash ansible-playbook site.yml --check # 先演练 ansible-playbook site.yml --limit 10.0.0.21 ``` ## 验证 ```bash ansible-playbook site.yml --syntax-check ansible all -m command -a "systemctl is-active nginx" ``` ## 回滚 playbook 本身没有统一回滚,靠写反向任务或者备份原文件。 ```yaml - name: 备份 copy: src: /etc/nginx/nginx.conf dest: /etc/nginx/nginx.conf.bak remote_src: yes ``` ## 坑 - **`--check` 不等于安全**,用 `shell` 模块时 check 也会真跑。 - 用 `shell` 而不是 `command`/`copy`/`template`,就丢掉了幂等性。 - 忘记 `become: yes`,任务全报权限不足。 - 目标机没 python,`ping` 直接失败。 - `gather_facts` 在几百台时很慢,可以关掉。 - 改完配置不 `handlers` 触发 reload,服务还是旧配置。