ansible应通过系统包管理器安装:rhel/centos 7用yum install ansible,rhel 8+/rocky/almalinux用dnf install ansible-core,ubuntu/debian用apt install ansible,避免pip安装引发python环境冲突。

直接用系统包管理器装,别 pip install ansible。绝大多数发行版的官方仓库已提供稳定、兼容的 ansible-core 或 ansible 包;pip 安装极易引发 Python 环境冲突,尤其在 RHEL 8+/CentOS Stream/Ubuntu 22.04+ 上,常见报错如 ImportError: cannot import name 'soft_unicode',根源是 pip 装的 Ansible 与系统自带的 Jinja2 版本不匹配。
不同发行版该执行哪条安装命令
命令差异主要取决于仓库结构和包名拆分(Ansible 2.10+ 后 ansible-core 是最小运行时,ansible 包含常用集合):
- Ubuntu/Debian:运行
sudo apt update && sudo apt install ansible;若需最新版且接受风险,可加 PPA:sudo add-apt-repository --yes --update ppa:ansible/ansible && sudo apt install ansible - RHEL/CentOS/Rocky/AlmaLinux 8+:先启用 EPEL:
sudo dnf install epel-release,再装sudo dnf install ansible-core(注意是ansible-core,不是旧版ansible) - RHEL/CentOS 7:启用 EPEL 后执行
sudo yum install ansible - Fedora:直接
sudo dnf install ansible
装完立刻运行 ansible --version,确认输出中包含 configured module search path —— 若为空,说明模块路径未正确初始化,后续会报 MODULE FAILURE。
inventory 文件写错会导致所有命令失败
Ansible 不是装完就能跑通的工具,它默认依赖 SSH 连通性和合法 inventory。最常见错误是执行 ansible all -m ping 报 UNREACHABLE! => {"msg": "Failed to connect to the host via ssh"},其实跟 Ansible 无关,纯属环境没配好:
- 确保目标主机
sshd正在运行,且防火墙放行 22 端口:sudo ufw allow 22(Ubuntu)或sudo firewall-cmd --permanent --add-service=ssh && sudo firewall-cmd --reload(RHEL系) - 本地生成密钥对:
ssh-keygen -t ed25519 -f ~/.ssh/id_ansible -N "",再用ssh-copy-id -i ~/.ssh/id_ansible.pub user@host推送公钥 - inventory 文件必须有合法格式,例如当前目录下的
inventory文件内容应为:[web]<br>192.168.1.10<br>192.168.1.11
——不能漏方括号,IP 不能带空格或注释符号 - 测试时显式指定 inventory:
ansible all -i ./inventory -m ping,避免误读系统默认路径/etc/ansible/hosts
ansible-core 和 ansible 包的区别决定你能用什么模块
从 Ansible 2.10 开始,项目已拆分:ansible-core 只含引擎和基础模块(如 ping、copy、shell),而 community.mysql.mysql_user、amazon.aws.ec2_instance 等高级功能全在第三方 collection 里:
- 检查已装集合:
ansible-galaxy collection list;若输出为空或缺失关键集合,说明只有ansible-core - 装一个常用集合:
ansible-galaxy collection install community.mysql(需网络连通) - 某些发行版(如 RHEL 8+)默认只装
ansible-core,即使你敲dnf install ansible也只会拉取ansible-core—— 这不是 bug,是设计如此 - 若要用
ansible.builtin.apt但目标是 RHEL 主机,Playbook 会静默跳过(因模块不适用),务必用when: ansible_os_family == "Debian"做条件控制
真正容易被忽略的是:inventory 中主机定义里的连接参数(如 ansible_user、ansible_ssh_private_key_file)若写错路径或权限不对(比如私钥文件 mode 不是 600),ansible 会静默 fallback 到密码认证,然后失败;而 ControlPersist 在 SSH 配置中启用时,可能导致 ad-hoc 命令复用旧连接并卡住 —— 生产环境建议在 ~/.ssh/config 中显式禁用:
Host *<br> ControlPersist no











