一、服务器需要Python环境
被管理的服务器(目标主机)默认需要安装 Python,因为 Ansible 通过 SSH 在目标主机上执行模块时,大多数模块依赖 Python 环境。
若目标主机无 Python,可先用 raw
模块安装:
# 适用于 Ubuntu/Debian
ansible server -m raw -a "apt-get install -y python3"
# 适用于 CentOS/RHEL
ansible server -m raw -a "yum install -y python3"
部分模块不依赖 Python(如 raw
、script
、command
、shell
):
- name: 无 Python 环境下执行命令
hosts: servers_without_python
gather_facts: false # 禁用收集 facts(依赖 Python)
tasks:
- name: 执行 shell 命令
shell: uptime
建议在目标主机上安装 Python,以充分利用 Ansible 的全部功能。对于无法安装 Python 的环境,可通过
raw
模块执行基础命令,但会受限模块功能。
二、指纹认证的问题
由于Ansible
在执行任何命令时都会先通过SSH
连接目标主机,而首次通过SSH
连接主机时,需要进行指纹确认,但Ansible
默认无法交互式输入yes
,导致任务卡住并失败。
解决方法(1):
提前在控制节点上手动
SSH
到每个目标主机,并输入yes
确认指纹:
ssh root@192.168.100.10 # 首次连接时输入yes
ssh root@192.168.100.11 # 重复操作所有主机
解决方法(2):
禁止严格主机密钥检查(测试环境适用)
# 临时生效(命令行)
ansible all -m ping --ssh-common-args='-o StrictHostKeyChecking=no'
# 永久生效(编辑/etc/ansible/ansible.cfg)
[defaults]
host_key_checking = False
# 变量的方式(编辑/etc/ansible/hosts)
[web_servers]
192.168.100.10 ansible_ssh_common_args='-o StrictHostKeyChecking=no'
192.168.100.11 ansible_ssh_common_args='-o StrictHostKeyChecking=no'
[db_servers]
192.168.100.12 ansible_ssh_common_args='-o StrictHostKeyChecking=no'
192.168.100.13 ansible_ssh_common_args='-o StrictHostKeyChecking=no'
三、没有指定用户名和密码的问题
因为我们并没有指定用户名和密码,所以SSH
无法正常连接。
解决方法(1):
命令行直接指定密码(临时使用),
-k
参数会让Ansible
交互式提示输入密码
ansible all -m ping -k
解决方法(2):
在主机清单中通过变量配置密码
[web_servers]
192.168.100.10 ansible_user=root ansible_password=Huawei@123
192.168.100.11 ansible_user=root ansible_password=Huawei@123
[db_servers]
192.168.100.12 ansible_user=root ansible_password=Huawei@123
192.168.100.13 ansible_user=root ansible_password=Huawei@123
四、Ansible模块依赖的问题
[WARNING]: Platform linux on host 192.168.100.10 is using the discovered Python
interpreter at /usr/bin/python3, but future installation of another Python interpreter
could change this. See
https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html for
more information.
这个警告(WARNING)表明 Ansible 在目标主机 192.168.100.10 上自动发现了 Python 解释器(/usr/bin/python3),
但未来如果系统 Python 环境发生变化(例如安装了其他版本的 Python),可能会导致 Ansible 执行失败。
Ansible 模块依赖 Python 运行,默认会通过以下方式自动探测目标主机的 Python 路径:尝试 python
、python3
、/usr/bin/python
等常见路径。
解决方法(1):在清单中显式指定 Python 解释器
# 静态清单文件(INI 格式)
[web_servers]
192.168.100.10 ansible_python_interpreter=/usr/bin/python3
解决方法(2):全局配置(ansible.cfg)
[defaults]
interpreter_python = /usr/bin/python3
解决方法 (3):完全禁用警告(不建议使用)
[defaults]
interpreter_python = auto_legacy_silent
五、配置免密登录
由于ansible
每次执行命令时都需要SSH
连接到目标主机,而传统配置用户名和密码的方式太过繁琐,所以并不推荐。
推荐使用公钥认证(免密认证)的方式进行连接,如下:
配置免密登录
### 在控制节点上生成密钥对
ssh-keygen -t rsa
### 将公钥复制到目标主机,需要输入ssh密码
ssh-copy-id root@192.168.100.10
### 验证免密登录是否正常,如果直接登录成功(无需密码),说明配置正确
ssh root@192.168.100.10
测试
ansible
免密连接
vim /etc/ansible/hosts
[web_servers]
192.168.0.10
192.168.0.11
[db_servers]
192.168.0.12
192.168.0.13
ansible all -m ping