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

如何配置Ansible使剧本中其他主机感知到被救援(rescue)的故障主机

如何在Ansible Rescue场景下让其他主机知晓故障主机

这个问题我之前也碰到过,确实用ansible_play_hosts_all减ansible_play_batch的方法在rescue场景下行不通——因为一旦进入rescue块处理故障,Ansible会把这台主机的状态从「失败」改成「已恢复」,所以ansible_play_batch里还是会包含它,差值自然是空的。

下面给你两个实用的解决方案:

方案1:通过临时组标记故障主机

利用add_host模块在rescue块中将故障主机添加到一个临时组,后续所有主机都可以通过这个临时组直接获取故障主机列表,非常直观。

示例Playbook:

---
- hosts: host1, host2
  gather_facts: false
  tasks:
    - block:
        - name: 模拟主机故障
          shell: /bin/false
          when: inventory_hostname == 'host1'
      rescue:
        - name: 执行故障恢复操作
          shell: /bin/true
          
        - name: 将故障主机加入临时组
          add_host:
            name: "{{ inventory_hostname }}"
            groups: failed_hosts
          # 确保是因为任务失败进入rescue流程
          when: ansible_failed_task is defined

    - name: 所有主机查看故障主机列表
      debug:
        msg: "需要恢复的故障主机: {{ groups['failed_hosts'] | default([]) }}"

方案2:通过主机事实标记故障主机

在rescue块中给故障主机设置一个自定义事实(比如is_failed),然后其他主机可以通过遍历所有主机的hostvars来收集带有该标记的主机,灵活性更强。

示例Playbook:

---
- hosts: host1, host2
  gather_facts: false
  tasks:
    - block:
        - name: 模拟主机故障
          shell: /bin/false
          when: inventory_hostname == 'host1'
      rescue:
        - name: 执行故障恢复操作
          shell: /bin/true
          
        - name: 标记当前主机为故障主机
          set_fact:
            is_failed: true

    - name: 列出所有故障主机
      debug:
        msg: "故障主机列表: {{ groups['all'] | select('extract', hostvars) | selectattr('is_failed', 'defined') | map(attribute='inventory_hostname') | list }}"
      run_once: true

两种方案的特点

  • 方案1的临时组在整个Playbook运行期间都有效,适合需要多次引用故障主机的场景;
  • 方案2通过主机事实存储标记,不需要依赖临时组,适合只需要一次性收集故障主机的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 15:52:49