最稳妥方式是用系统包管理器安装:Ubuntu/Debian执行sudo apt update && sudo apt install ansible,RHEL/CentOS 8+执行sudo dnf install ansible-core,CentOS 7需先启用EPEL再yum install ansible;装完运行ansible --version和ansible localhost -m ping验证。

直接用系统包管理器安装最稳妥
绝大多数现代 Linux 发行版的官方仓库都已收录 ansible,无需手动编译或 pip 混乱依赖。优先走系统包管理器,能自动处理 python3、openssh、libyaml 等底层依赖,避免后续执行 ansible --version 报 ModuleNotFoundError 或 ImportError: No module named 'yaml'。
常见发行版命令如下:
- Ubuntu/Debian:
sudo apt update && sudo apt install ansible - RHEL/CentOS 8+ / Rocky/AlmaLinux:
sudo dnf install ansible-core(注意:RHEL 9+ 默认装的是ansible-core,不含ansible全功能包) - CentOS 7(EOL但仍有使用):
sudo yum install epel-release && sudo yum install ansible
装完立刻验证:ansible --version 应输出版本号,且 ansible localhost -m ping 返回 SUCCESS。若提示 permission denied (publickey),说明 SSH 密钥未配置——这不是 Ansible 安装问题,先跳过,后面再配。
别轻易用 pip install ansible
pip install ansible 表面简单,实际埋雷最多:它会拉取最新版(如 9.x),但可能与系统 Python 的 distutils、setuptools 版本冲突;更常见的是覆盖掉系统自带的 ansible-core,导致 ansible-galaxy 命令消失或 ansible-playbook 找不到内置模块。
除非你明确需要某特定版本(比如要兼容旧 playbook),否则只在以下情况考虑 pip:
- 开发测试环境,且用
venv隔离:python3 -m venv ~/ansible-env && source ~/ansible-env/bin/activate && pip install ansible==8.9.0 - 系统无网络访问仓库(离线环境),且已提前导出 wheel 包
切记:不要用 sudo pip install,它会污染系统 Python site-packages,后续升级系统时极易报错。
安装后必须检查 ssh-keyscan 和 inventory 文件
Ansible 默认通过 SSH 连目标主机,但很多人装完就跑 ansible all -m ping 却卡住或失败,根本原因不是 Ansible 没装好,而是没准备好连接前提。
两个关键动作缺一不可:
- 确保控制机可免密登录目标机:运行
ssh-keygen -t ed25519(若无密钥),再ssh-copy-id user@target;若目标是localhost,也要确认ssh localhost不要输密码 - 创建最小
inventory文件(如hosts):[all] localhost ansible_connection=local
,然后加-i hosts参数运行,避免 Ansible 默认读取空或不存在的/etc/ansible/hosts
常见错误现象:UNREACHABLE! => {"msg": "Failed to connect to the host via ssh..."},90% 是 SSH 配置问题,不是 Ansible 安装问题。
CentOS/RHEL 中 ansible-core 和 ansible 的区别不能忽略
RHEL 8+ 及衍生版把 Ansible 拆成两个包:ansible-core(含核心引擎、基础模块、CLI 工具)和 ansible(额外含大量社区模块、ansible-galaxy CLI、ansible-test 等)。如果你只需要写简单 playbook 控制服务器,ansible-core 够用;但一旦要用 community.mysql、amazon.aws 等集合,就必须装完整版 ansible 包或通过 ansible-galaxy collection install 补充。
验证方式:ansible --version 输出里带 config file = /etc/ansible/ansible.cfg 且 configured module search path 列出多个路径,说明是完整版;若只有 ansible-core,则 ansible-galaxy 命令不存在,collections 目录也为空。
补全方法(RHEL/Rocky 9):sudo dnf install ansible(需启用 crb 或 powertools 仓库);若仓库不可用,改用 pipx install ansible(比全局 pip 更安全)。
真正容易被忽略的点是:Ansible 安装只是起点,inventory 结构、SSH 认证粒度、Python 解释器路径(ansible_python_interpreter)这些配置项,往往在第一次 ansible-playbook 失败时才暴露出来。别急着重装,先看 ansible -vvv 输出里的连接细节。


















