Ansible - Ansible安装与入门配置
发布时间:2026-05-03 16:02
解决Ansible自动化工具从零安装、配置到首次连接被管节点的全流程问题,涵盖CentOS/RHEL与Ubuntu两大主流发行版的路径差异,让你绕过常见坑,30分钟跑通第一个Playbook。
Ansible安装与入门配置:从零跑通第一个自动化任务
一、前言
搞过自动化的人都知道,第一次装Ansible时被各种Python依赖、包管理冲突、SSH配置折腾到心态爆炸的环境不在少数。这篇文章不整那些"什么是Ansible"的废话,直接干:装好、配置、连上第一台机器、执行第一个任务。
二、操作步骤
步骤1:确认环境并安装Python环境
Ansible依赖Python 3.8+,先检查系统环境。
CentOS/RHEL 8+:
$ python3 --version
Python 3.9.5
$ sudo dnf install python3 python3-pip -y
已安装并且是最新版本,无需处理。
Package python3-3.9.5-4.el8.x86_64 is already installed.
Ubuntu 22.04+:
$ python3 --version
Python 3.10.12
$ sudo apt update && sudo apt install python3 python3-pip -y
正在读取软件包列表... 完成
生成依赖树... 完成
python3 已达到最新版本 (3.10.6-1)。
pip 3.10.12
步骤2:通过pip安装Ansible
官方推荐pip安装,可以获取最新稳定版本。
$ sudo pip3 install ansible
Collecting ansible
Downloading ansible-10.1.0 (py3)
Collecting ansible-core==2.15.10
Downloading ansible-core-2.15.10.tar.gz (2.1 MB)
...
Installing collected packages: ansible, ansible-core, resolvconf
Successfully installed ansible-10.1.0
$ ansible --version
ansible [core 2.15.10]
config file = None
configured module search path = ['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
ansible python module location = /usr/local/lib/python3.9/site-packages/ansible
ansible collection location = /usr/local/lib/python3.9/site-packages/ansible/collections/ansible_collections
executable location = /usr/local/lib/bin/ansible
python version = 3.9.5
步骤3:创建工作目录和配置文件
生产环境不要在home目录随便搞,创建个专门的ansible工作区。
$ mkdir -p ~/ansible-prod && cd ~/ansible-prod
$ ls -la
总用量 0
drwxr-xr-x 4 root root 4096 Sep 20 10:30:02 .
drwxr-xr-x 2 root root 4096 Sep 20 10:30:02 .
drwxr-xr-x 6 root root 4096 root 4096 Sep 20 10:30:02 ..
创建ansible.cfg配置文件:
$ cat > ansible.cfg << 'EOF'
[defaults]
inventory = ./inventory
host_key_checking = False
timeout = 30
gather_facts = False
[privilege_escalation]
become = True
become_method = sudo
become_user = root
become_ask_pass = False
EOF
$ cat ansible.cfg
[defaults]
inventory = ./inventory
host_key_checking = False
timeout = 30
gather_facts = False
[privilege_escalation]
become = True
become_method = sudo
become_user = root
become_ask_pass = False
步骤4:配置inventory主机清单
定义要管理的主机。这里用两台测试机做示例,生产环境记得替换成真实IP。
$ cat > inventory << 'EOF'
[webServers]
192.168.1.101 ansible_user=deploy ansible_ssh_private_key_file=~/.ssh/id_rsa
192.168.1.102 ansible_user=deploy ansible_ssh_private_key_file=~/.ssh/id_rsa
[dbServers]
192.168.1.201 ansible_user=deploy ansible_ssh_private_key_file=~/.ssh/id_rsa
[all:vars]
ansible_python_interpreter=/usr/bin/python3
EOF
[webServers]
192.168.1.101 ansible_user=deploy ansible_ssh_private_key_file=~/.ssh/id_rsa
192.168.1.102 ansible_user=deploy ansible_ssh_private_key_file=~/.ssh/id_rsa
[dbServers]
192.168.1.201 ansible_user=deploy ansible_ssh_private_key_file=~/.ssh/id_rsa
[all:vars]
ansible_python_interpreter=/usr/bin/python3
步骤5:配置SSH免密连接
被管节点如果还没配置过SSH公钥,先做这一步。使用ssh-copy-id工具,密码方式部署公钥。
首次连接需输入密码:
$ ssh-copy-id -i ~/.ssh/id_rsa.pub deploy@192.168.1.101
/usr/bin/ssh-copy-id: INFO: Source of key(s) offered: /root/.ssh/id_rsa.pub
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that already exist on the remote system.
/usr/bin/ssh-copy-id: INFO: 1 of 1 node(s) succeeded
deploy@192.168.1.101's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh -i '~/.ssh/id_rsa' 'deploy@192.168.1.101'"
验证SSH连接:
$ ssh -o ConnectTimeout=5 deploy@192.168.1.101 "hostname"
web-server-01
步骤6:测试Ansible连通性
用ping模块快速验证所有主机连通性,不需要登录目标机执行命令。
$ cd ~/ansible-prod
$ ansible all -m ping -i inventory
192.168.1.101 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python3"
},
"changed": false,
"ping": "pong"
}
192.168.1.102 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python3"
},
"changed": false,
"ping": "pong"
}
192.168.1.201 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python3"
},
"changed": false,
"ping": "pong"
}
如果看到SUCCESS和pong字样,恭喜你已成功连上所有被管节点。
步骤7:执行第一个实际任务——批量查看磁盘
用command模块在所有web服务器上执行df命令:
$ ansible webServers -m command -a "df -h" -i inventory
192.168.1.101 | CHANGED | rc=0 >>
文件系统 容量 已用 可用 已用% 挂载点
devtmpfs 16G 0 16G 0% /dev
tmpfs 16G 0 16G 0% /dev
/dev/vda1 100G 45G 55G 45% /
tmpfs 2.0G 0 2.0G 0% /dev/shm
192.168.1.102 | CHANGED | rc=0 >>
文件系统 容量 已用 可用 已用% 挂载点
devtmpfs 16G 0 16G 0% /dev
tmpfs 16G 0 16G 0% /dev
/dev/vda1 200G 80G 120G 40% /
tmpfs 2.0G 0 2.0G 0% /dev/shm
步骤8:编写第一个Playbook实现批量部署
真正干活还是得用Playbook,创建一个Nginx安装的配置文件:
$ cat > deploy-nginx.yml << 'EOF'
---
- name: Install and configure Nginx
hosts: webServers
become: true
tasks:
- name: Install Nginx package
package:
name: nginx
state: present
- name: Start Nginx service
service:
name: nginx
state: started
enabled: true
- name: Copy custom index page
template:
src: index.html.j2
dest: /var/www/html/index.html
notify: Reload Nginx
handlers:
- name: Reload Nginx
service:
name: nginx
state: reloaded
EOF
---
- name: Install and configure Nginx
hosts: webServers
become: true
tasks:
- name: Install Nginx package
package:
name: nginx
state: present
- name: Start Nginx service
service:
name: nginx
state: started
enabled: true
- name: Copy custom index page
template:
src: index.html.j2
dest: /var/www/html/index.html
notify: Reload Nginx
handlers:
- name: Reload Nginx
service:
name: nginx
state: reloaded
执行Playbook:
$ ansible-playbook deploy-nginx.yml -i inventory
PLAY [Install and configure Nginx] *********************************************************************
TASK [Gathering Facts] *******************************************************************************
ok: [192.168.1.101]
ok: [192.168.1.102]
TASK [Install Nginx package] **************************************************************************
ok: [192.168.1.101]
ok: [192.168.1.102]
TASK [Start Nginx service] ***************************************************************************
ok: [192.168.1.101]
ok: [192.168.1.102]
PLAY RECAP *******************************************************************************************
192.168.1.101 : ok=3 changed=0 unreachable=0 failed=0
192.168.1.102 : ok=3 changed=0 unreachable=0 failed=0
三、常见问题FAQ
Q:连不上目标机,报"Failed to connect to the host via ssh: Permission denied"
这问题十有八九是SSH密钥没配对。先确认公钥是否已经部署到目标机:ssh-copy-id user@targetIP。再检查inventory里写的路径是否正确指向私钥文件,私钥权限必须是600。如果用了跳板机或者非标准端口,得在inventory里加ansible_ssh_common_args或者在ansible.cfg里配置代理转发。
Q:目标机跑的是Python3,但Ansible报"module default not found in library path"
这是Ansible找不到Python解释器。在inventory里加上ansible_python_interpreter=/usr/bin/python3变量,或者在ansible.cfg的[defaults]段加上interpreter_python=auto_silent。有些精简镜像默认没装python,需要先手动装上yum install python3或apt install python3。
Q:第一次连某台机器要输入yes/no,确认后下次又要输
SSH首次连接会问yes/no做主机指纹确认,但在非交互模式下会卡住。在ansible.cfg里加了host_key_checking = False后就不会再问了。生产环境建议还是用known_hosts管理指纹,这个参数只是开发测试环境用的。
Q:Playbook执行报"Could not find module"或者"unsupported parameter for module"
这是Ansible版本和模块参数不匹配。高版本Ansible废弃了一些旧参数,比如yum模块改成了通用的package,service模块的enabled参数也有调整。先确认控制机的版本:ansible --version,然后去官方文档查对应版本的模块语法。
四、总结
核心要点:
- 通过pip安装Ansible可获取最新稳定版本,dnf/apt方式受制于仓库更新速度
- ansible.cfg和inventory要放在同一目录,启动时默认读取当前目录配置
- SSH免密是基操,ssh-copy-id工具能一键完成公钥部署
- 先用ping模块验证连通性,再跑实际任务,这是基本排查流程
- package模块比yum/apt更通用,能跨发行版工作
延伸阅读:
- 官方文档:Ansible Documentation
- 进阶主题:Ansible Vault加密敏感数据、Roles组织Playbook结构、Inventory动态脚本
- 推荐工具:ansible-lint代码检查、ARA记录执行历史、AWX/Web UI管理界面