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

Ansible Playbook主机不可达场景下触发block的rescue块执行问题

Ansible block/rescue 主机不可达场景触发方案

你可以通过「先忽略不可达错误、再手动判断触发失败」的逻辑实现需求,既不会让playbook全局终止,也能正常触发rescue块。

实现逻辑

  • 给启动Apache的任务添加ignore_unreachable: yes参数,避免主机不可达时直接终止playbook,同时注册任务执行结果变量
  • 在Apache启动任务后新增失败断言任务,若检测到主机不可达则主动抛出失败,触发rescue逻辑
  • 主机可达时断言任务自动跳过,不影响原有场景1、2的原生block/rescue执行逻辑

调整后的Playbook示例

tasks:
  - name: "Task 1"
  ...

  - name: "Start Apache"
    block:
    - name: "Ensure Apache is started"
      ansible.builtin.service:
          name: apache2
          state: started
      ignore_unreachable: yes
      register: apache_start_result

    - name: "判断主机是否不可达"
      ansible.builtin.fail:
        msg: "目标主机 {{ inventory_hostname }} SSH连接失败"
      when: apache_start_result.unreachable is defined and apache_start_result.unreachable

    - name: "Wait for website to come up on this host"
      delegate_to: 127.0.0.1
      uri:
        url: "http://{{inventory_hostname}}"
        return_content: yes
      register: _result
      until: _result.content != '\"\"'
      retries: 5
      delay: 5
  
    rescue:
    - name: "Do Something"
      ...

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 10:06:03