Ansible教程:Ad-hoc 命令用法-yum模块详解(适用centos) 作者:马育民 • 2026-09-25 21:06 • 阅读:10001 # 介绍 **yum模块是CentOS7/RHEL7系专用包管理模块**,具备**幂等性**(重复执行不会报错,已安装就不重复安装),底层封装`yum`,优于直接用shell/command模块执行安装软件。 ### CentOS8+ 推荐 `dnf` 模块,用法几乎和 yum 一致。 # 基础语法 ```bash ansible 主机组/主机 -m yum -a "参数" ``` **解释:** - `-m yum`:指定使用 yum 模块 - `-a "xxx"`:模块参数 # 常用参数 | 参数 | 说明 | |---|---| | `name` | 软件包名称,可以带版本,多个包用逗号分隔 | | `state` | 状态:`present`(安装,默认) / `latest`(更新到最新) / `absent`(卸载) | | `update_cache` | `yes/no`,安装前执行 `yum clean all && yum makecache`,刷新yum源缓存 | | `disable_gpg_check` | `yes/no`,是否关闭GPG校验,内网源常用 | | `enablerepo` | 指定启用哪个repo安装包 | | `disablerepo` | 安装时临时禁用某个repo | | `list` | 可选:`installed`/`updates`/`available`,列出包信息,不能和name一起用 | **注意:** yum模块**不是直接调用shell的yum命令**,是ansible内置模块,幂等性(多次执行不会重复安装)。 --- # 安装例子 ### 1. 安装软件包(present,存在即可,不升级) ```bash ansible web -m yum -a "name=httpd state=present" ``` 多个包一起安装: ```bash ansible web -m yum -a "name=httpd,php state=present" ``` ### 2. 安装指定版本 ```bash ansible web -m yum -a "name=httpd-2.4.6 state=present" ``` ### 3. 升级到最新版本 latest ```bash ansible web -m yum -a "name=httpd state=latest" ``` ### 4. 安装前刷新yum缓存 ```bash ansible web -m yum -a "name=nginx state=present update_cache=yes" ``` ### 5. 临时启用指定repo安装 ```bash ansible web -m yum -a "name=nginx state=present enablerepo=epel" ``` ### 6. 关闭GPG校验(内网源场景) ```bash ansible web -m yum -a "name=xxx state=present disable_gpg_check=yes" ``` ### 7. 查询已安装包(list参数) ```bash # 查询所有已安装 ansible web -m yum -a "list=installed" # 查询可更新包 ansible web -m yum -a "list=updates" ``` # 卸载例子 ```bash ansible web -m yum -a "name=httpd state=absent" ``` # 返回结果字段说明 执行后常见返回信息: - `changed: true`:包发生变更(安装/卸载/升级) - `changed: false`:包状态已经符合预期,无操作(幂等特性) - `rc`:返回码,0=成功;非0=失败 - `results`:yum操作详细输出 # 常见坑 1. **CentOS8 不要再用yum模块,改用 dnf** ```bash ansible web -m dnf -a "name=nginx state=present" ``` 2. name写版本时,包名和版本不能有空格 ✅ `name=httpd-2.4.6` ❌ `name=httpd - 2.4.6` 3. update_cache=yes 只是刷新缓存,**不会自动升级系统包** 4. yum模块不能直接执行 `yum groupinstall` 安装软件组,软件组要用 `name="@Development Tools"` ```bash ansible web -m yum -a 'name="@Development Tools" state=present' ``` # 对比 shell 方式 ```bash # shell方式:没有幂等性,每次都会执行yum install ansible web -m shell -a "yum install -y nginx" ``` 推荐yum模块:幂等、输出结构化、ansible会自动判断是否已安装。 原文出处:/show_1GW477NgfLam.html