Ansible不直接安装系统补丁,而是调用目标系统包管理器(如yum、apt、dnf)实现;推荐按系统类型分组并显式使用对应模块(如RHEL 8+用dnf模块启用security: true,Ubuntu/Debian用apt模块指定default_release为-security源),并验证补丁生效(如检查reboot_required、内核版本或errata列表,必要时重启服务)。

Ansible 本身不直接安装系统补丁——它调用目标系统的包管理器(如 yum、apt、dnf)来完成,关键在于选对模块、设对参数、避开权限和状态陷阱。
用 package 模块还是 yum/apt 模块?
Ansible 2.10+ 推荐统一用 package 模块,它会自动适配目标系统的包管理器(yum for RHEL/CentOS 7, dnf for RHEL 8+, apt for Debian/Ubuntu)。但实际批量打补丁时,package 的行为不够可控:
-
state: latest会升级所有包,不等于“只装安全补丁” - 无法过滤 CVE 或 errata(如 RHEL 的
dnf update --security) - Debian 系不支持
--security标志,得靠apt模块 +upgrade: safe或手动过滤
所以更稳妥的做法是:按系统类型分组,显式调用对应模块。
RHEL/CentOS 批量安装安全补丁(含 errata)
RHEL 系补丁常以 errata(如 RHSA-2024:1234)形式发布,单纯 yum update 不保证拉取安全更新。需结合 yum 模块与 update_cache: yes,或用 command 调用 dnf update --security --advisory=RHSA-*(RHEL 8+):
- name: Install security patches on RHEL 8+
dnf:
name: "*"
state: latest
security: true
update_cache: true
when: ansible_facts['distribution_major_version'] | int >= 8注意:security: true 仅在 dnf 模块中有效,yum 模块不支持;若用 command 执行 dnf,记得加 become: true 和 ignore_errors: false,否则失败不报错。
Debian/Ubuntu 只升级安全源里的包
Ubuntu/Debian 的安全更新走独立源(如 http://security.ubuntu.com),不能靠 apt upgrade 默认行为覆盖。必须先确保 /etc/apt/sources.list 启用了 -security 行,再用 apt 模块指定 upgrade: safe 或过滤源:
- name: Update apt cache and install security updates
apt:
upgrade: dist
default_release: "{{ ansible_distribution_release }}-security"
update_cache: true
when: ansible_facts['distribution'] in ['Debian', 'Ubuntu']常见坑:default_release 必须拼写准确(如 focal-security),否则 apt 会跳过安全源;另外 upgrade: dist 比 safe 更激进,但能覆盖跨版本安全修复,生产环境建议先测试。
补丁安装后验证是否真生效
Ansible 执行完不等于补丁已生效——内核更新要重启,某些服务(如 glibc)需 reload 进程。别只依赖模块返回的 changed 状态:
- 检查
reboot_required:用setup模块查ansible_facts['reboot_required'](仅部分 Linux 发行版支持) - 查内核版本变化:
command: uname -r对比 before/after - 查已安装的 errata:
command: yum updateinfo list security(RHEL)或apt list --upgradable 2>/dev/null | grep security(Ubuntu)
最易被忽略的是:补丁安装成功 ≠ 服务已使用新库。比如 openssl 升级后,Nginx 进程仍可能持旧版本内存映射,必须 systemctl reload nginx 或重启进程。

















