Ansible批量补丁更新需稳准安全:先确保Ansible安装、免密SSH和Inventory配置三件套跑通;再用ansible_facts['os_family']准确识别系统类型;最后编写含缓存更新、全包升级、条件重启的幂等Playbook,并通过标签、暂停确认、加密变量和分批执行增强可控性。

Ansible 是 Linux 批量补丁更新最实用的工具之一,关键不在“能不能做”,而在于“怎么稳、怎么准、怎么安全”。它不依赖客户端,靠 SSH 执行,天然适合运维环境;但若跳过几个基础环节,ansible all -m ping 都会失败,更别说打补丁了。
第一步:确保三件套跑通
这是所有补丁操作的前提,90% 的失败卡在这一步:
-
控制机装好 Ansible:Ubuntu/Debian 用
sudo apt install ansible;CentOS/RHEL 8+ 直接dnf install ansible-core,7 系需先配 EPEL 源 -
目标机开通免密 SSH:必须用
ssh-copy-id user@ip推公钥,不能手动复制;确认/etc/ssh/sshd_config中PubkeyAuthentication yes已启用,且.ssh目录权限为 700、authorized_keys为 600 -
Inventory 文件写对位置和格式:推荐在项目目录下新建
hosts,内容严格按 INI 格式,比如:
[patch_targets]
192.168.1.10 ansible_user=ops
192.168.1.11 ansible_user=ops
第二步:识别系统类型,避免硬编码翻车
别再用 ansible_distribution == "Ubuntu" 这类写法——新版 Ansible 已弃用该变量,且 Rocky、AlmaLinux 等发行版返回值不一致。应统一使用:
-
ansible_facts['os_family'] == "Debian"(覆盖 Ubuntu/Debian/Kali) -
ansible_facts['os_family'] == "RedHat"(覆盖 CentOS/RHEL/Rocky/AlmaLinux) - 如需版本判断,加
and ansible_facts['distribution_major_version'] | int >= 8
注意:Playbook 默认收集 facts,但如果写了 gather_facts: false,这些变量就为空,补丁任务会因条件判断失效。
第三步:编写安全、幂等的补丁 Playbook
下面是一个生产可用的最小补丁剧本(patch.yml),兼顾 Debian 和 RHEL 系统,含缓存更新、全包升级、内核更新后自动重启逻辑:
---
- name: Apply security updates and reboot if needed
hosts: patch_targets
become: true
gather_facts: true
tasks:
- name: Update package cache (Debian)
apt:
update_cache: true
when: ansible_facts['os_family'] == "Debian"
<pre class="brush:php;toolbar:false;">- name: Update package cache (RHEL)
yum:
update_cache: true
when: ansible_facts['os_family'] == "RedHat"
- name: Upgrade all packages
package:
name: "*"
state: latest
- name: Check if reboot required (Debian)
command: /usr/bin/test -f /var/run/reboot-required
ignore_errors: true
register: reboot_check_deb
when: ansible_facts['os_family'] == "Debian"
- name: Check if reboot required (RHEL)
command: /usr/bin/systemctl is-system-running | grep -q 'degraded\|maintenance'
ignore_errors: true
register: reboot_check_rhel
when: ansible_facts['os_family'] == "RedHat"
- name: Reboot host
reboot:
msg: "Security update applied, rebooting"
reboot_timeout: 600
post_reboot_delay: 30
when: >
(ansible_facts['os_family'] == "Debian" and reboot_check_deb.rc == 0) or
(ansible_facts['os_family'] == "RedHat" and reboot_check_rhel.rc == 0)
执行命令:ansible-playbook -i hosts patch.yml --limit 192.168.1.10 可指定单台灰度验证,确认无误后再去掉 --limit 全量执行。
第四步:增强可控性与安全性
补丁不是越快越好,而是要可观察、可中断、可回退:
-
加标签分阶段:在 task 上加
tags: [update, reboot],执行时用--tags update先只更新不重启 -
敏感操作加确认:在 reboot 任务前加
pause: prompt="Reboot {{ inventory_hostname }}? (y/n)",人工把关关键节点 -
密码或密钥不写明文:如需提权密码,用
ansible-vault create group_vars/all/vault.yml加密存储,执行时加--ask-vault-pass -
避免全量重启风暴:用
serial: 2控制每次只更新 2 台,防止服务大面积中断











