Ansible 是无代理(Agentless)的自动化运维工具:SSH 连上就能管成百上千台机器。系列 15 篇从入门写到 CI/CD,本篇先把环境跑通。
一、核心概念
控制节点(Control Node):装 Ansible 的机器(Linux/macOS)
被管节点(Managed Node):被管理的服务器(只需 SSH + Python)
清单(Inventory):主机列表
模块(Module):幂等的操作单元(yum/copy/service…)
任务(Task)→ 剧本(Playbook)→ 角色(Role)
| 特性 | 说明 |
|---|---|
| 无代理 | 被管机不装任何东西(SSH + Python) |
| 幂等 | 重复执行结果一致(已装的不再装) |
| 批量 | 一条命令操作全组主机 |
| 模块化 | 3000+ 官方模块,YAML 描述即代码 |
二、安装(控制节点)
# 方式1:pip(推荐,版本新)
pip3 install ansible
pip3 install ansible-core # 只装核心
# 方式2:yum(CentOS/RHEL)
yum install -y epel-release
yum install -y ansible
# 验证
ansible --version
# ansible [core 2.16.x]
# python version = 3.x.x
三、免密配置(SSH)
# 1. 生成密钥(控制节点)
ssh-keygen -t ed25519 -C "ansible"
# 2. 推公钥到被管机
ssh-copy-id root@192.168.1.10
ssh-copy-id root@192.168.1.11
# 3. 验证免密
ssh root@192.168.1.10 "hostname"
四、最小配置
# /etc/ansible/hosts(或项目 hosts 文件)
[web]
192.168.1.10
192.168.1.11 ansible_user=root ansible_ssh_private_key_file=~/.ssh/id_ed25519
五、第一条命令
# 语法:ansible <主机组> -m <模块> -a "<参数>"
ansible all -m ping
# 192.168.1.10 | SUCCESS => { "ping": "pong" }
# 192.168.1.11 | SUCCESS => { "ping": "pong" }
ansible web -m command -a "hostname"
ansible all -m shell -a "uptime"
ping 模块验证的是SSH 连通 + Python 可用(不是 ICMP)。
六、配置优先级
ANSIBLE_CONFIG 环境变量 > ./ansible.cfg(当前目录)
> ~/.ansible.cfg(家目录)> /etc/ansible/ansible.cfg
# 项目级 ansible.cfg(推荐,随代码走)
[defaults]
inventory = ./hosts
host_key_checking = False
retry_files_enabled = False
roles_path = ./roles
七、注意
- 被管节点需要 Python(CentOS 7 自带 2.7,新版 ansible 需配 interpreter);
- 非 root 用户要配 sudo 免密:
ansible_become=True ansible_become_pass; - host_key_checking=False 避免首次连接卡确认(生产可接受);
- Windows 被管机走 WinRM 而非 SSH(本文不展开)。
八、小案例:环境初始化一键脚本
#!/bin/bash
# ansible_init.sh:控制节点初始化 + 批量免密
IPS="192.168.1.10 192.168.1.11 192.168.1.12"
PASS=yourpassword # 生产建议用 sshpass 临时或直接人工推钥
# 1. 装 Ansible
pip3 install ansible -q
ansible --version | head -1
# 2. 生成密钥(已有则跳过)
[ -f ~/.ssh/id_ed25519 ] || ssh-keygen -t ed25519 -N "" -f ~/.ssh/id_ed25519
# 3. 批量推公钥(需要 sshpass 或手动逐台)
for ip in $IPS; do
ssh-copy-id -o StrictHostKeyChecking=no root@$ip
done
# 4. 生成 inventory
mkdir -p ~/ansible-lab
cat > ~/ansible-lab/hosts <<EOF
[web]
$IPS
EOF
# 5. 验证
cd ~/ansible-lab
ansible all -i hosts -m ping
五步:装工具 → 密钥 → 推公钥 → 写清单 → ping 验证 —— 半小时从零到可用。
九、总结
无代理 = SSH + Python;ansible all -m ping 是第一课;配置找 ansible.cfg(项目级优先);免密 + 清单 + 验证三步走。