深色模式
Ansible 入门:inventory 与 playbook 批量装软件
摘要:Ansible 不需要在被管机器装客户端,只要 SSH 通就能干活。本文从安装、免密、写 inventory 到跑通第一个批量安装 playbook,一步不落。
适用环境
- 控制机:Linux(AlmaLinux 9 / Ubuntu 22.04),需 Python 3
- 被管机:2 台以上 Linux,开启 SSH,22 端口可达
- 被管机需 Python 3(最小化系统先
dnf install -y python3)
操作步骤
1. 安装与 SSH 免密
bash
sudo dnf install -y ansible-core # Ubuntu: sudo apt install -y ansible
ssh-keygen -t ed25519 -C "ansible-control"
ssh-copy-id ops@192.168.1.11
ssh-copy-id ops@192.168.1.121
2
3
4
2
3
4
2. 写 inventory 清单
bash
mkdir -p ~/ansible && cd ~/ansible
cat > inventory.ini <<'EOF'
[web]
192.168.1.11
192.168.1.12
[all:vars]
ansible_user=ops
ansible_ssh_common_args='-o StrictHostKeyChecking=no'
EOF1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
3. 连通性测试
bash
ansible all -i inventory.ini -m ping # 全部返回 pong 即正常1
4. 写第一个 playbook
yaml
- name: Install and start nginx on web servers
hosts: web
become: true
tasks:
- name: Install nginx package
ansible.builtin.package:
name: nginx
state: present
- name: Ensure nginx is running and enabled
ansible.builtin.service:
name: nginx
state: started
enabled: true1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
5. 先演练再执行
bash
ansible-playbook -i inventory.ini install-nginx.yml --check --diff # 只预测
ansible-playbook -i inventory.ini install-nginx.yml # 真正执行1
2
2
危险
--check 并非对所有模块准确,command/shell 任务在 check 模式下会被跳过。生产务必先在测试机真实跑一遍。
验证
bash
ansible web -i inventory.ini -m command -a 'systemctl is-active nginx'1
- [ ]
ansible all -m ping全部返回 pong - [ ] playbook 执行结果
failed=0 - [ ] 被管机
systemctl is-active nginx返回 active
常见坑
SSH 首次连接卡住
默认等 host key 确认。在 inventory 里加 ansible_ssh_common_args,或本地先手动 ssh 一次。
become 提权失败
普通用户 sudo 需密码时用 -K 交互输入,或在 /etc/sudoers.d/ 配 NOPASSWD。
主机组名写错
- hosts: 必须与 inventory 组名完全一致,写错时提示 skipping: no hosts matched,不报错也不执行。