You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ansible如何按操作系统顺序补丁系统:先RedHat后Ubuntu

解决方案:分Play按操作系统家族顺序执行补丁

不需要修改动态库存,只需利用Ansible的**系统事实(facts)**和多Play结构,就能先完成RedHat节点补丁,再处理Ubuntu节点。核心是通过ansible_os_family变量区分系统类型,分两个Play顺序执行。

完整剧本示例

---
- name: 批量升级RedHat系列节点补丁
  hosts: all
  gather_facts: yes
  tasks:
    - name: 安装所有可用系统更新(RedHat/CentOS等)
      yum:
        name: '*'
        state: latest
      when: ansible_os_family == 'RedHat'
      become: yes

- name: 批量升级Ubuntu系列节点补丁
  hosts: all
  gather_facts: yes
  tasks:
    - name: 更新APT缓存并升级系统(Ubuntu/Debian等)
      apt:
        upgrade: dist
        update_cache: yes
        autoclean: yes
      when: ansible_os_family == 'Debian'
      become: yes

关键说明

  1. 多Play顺序执行:Ansible会严格按剧本中Play的先后顺序运行,第一个Play仅处理RedHat系节点,全部完成后才进入第二个Play处理Ubuntu节点,完全满足你的顺序要求。
  2. 系统事实自动筛选:ansible_os_family是Ansible自动收集的系统内置变量,RedHat系(含RHEL、CentOS等)值为RedHat,Ubuntu/Debian系值为Debian,无需手动标记主机。
  3. 权限控制:补丁操作需要管理员权限,因此加上become: yes切换至root执行。
  4. 优化Facts收集:如果觉得两次收集Facts冗余,可将第一个Play的gather_facts设为yes,第二个设为no——Facts会在第一个Play中收集并缓存,后续Play可直接复用。

旧剧本失效的常见原因

  • 未拆分Play:单个Play内主机执行顺序由库存随机决定,仅靠条件判断无法保证先RedHat后Ubuntu的全局顺序;
  • 错误匹配系统:硬编码ansible_distribution(如直接写RedHat或Ubuntu),而非用更通用的ansible_os_family,导致兼容范围狭窄;
  • 缺少权限:未添加become: yes,导致补丁命令因权限不足执行失败。

内容的提问来源于stack exchange,提问作者Eugenics

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 23:26:12