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
相关产品推荐
相关产品推荐

