Ansible 最大的好处是无 agent,靠 SSH 和 Python 就能管。规模不大、不想上复杂平台的环境很合适。
装和免密
yum install -y ansible ssh-keygen -t rsa ssh-copy-id root@10.0.1.21
控制机到所有被管机配好免密,这是前提,否则每次都要输密码。
写主机清单
[web] 10.0.1.21 ansible_user=root 10.0.1.22 ansible_user=root [db] 10.0.1.31 ansible_user=root
先测连通
ansible all -m ping -i hosts.ini
返回 SUCCESS 说明 SSH 和 Python 都正常。返回 UNREACHABLE 查网络和密钥,返回 FAILED 多半是被管机没有 python。
批量执行
ansible web -m shell -a "systemctl status nginx" -i hosts.ini ansible all -m shell -a "df -h /" -i hosts.ini
批量改配置用 copy 或 template 模块,比 shell 里的 sed 安全。
ansible web -m copy -a "src=nginx.conf dest=/etc/nginx/nginx.conf" -i hosts.ini ansible web -m service -a "name=nginx state=restarted" -i hosts.ini
注意
shell 模块不保证幂等,重复执行会重复生效,能不用就不用。大批量操作先拿一台机器试(--limit),确认没问题再全量。