Ansible:为何已救援任务未计入Playbook最终失败计数器?
问题描述
我有如下Playbook(已脱敏,核心逻辑保留):
- name: run command based on condition block: - name: run command based on condition command: *some curl command* when: *condition* register: out failed_when: 'rc != 0' debug: var=out rescue: - name: Set flag set_fact: flag="failed" when: "'FAILED' in out"
该Playbook会根据3个条件执行3次,block中的任务可能被跳过。根据Ansible文档:
如果block中发生错误且rescue任务执行成功,Ansible会恢复原任务的成功状态继续执行,但Playbook统计中仍会报告失败。
但测试时,我设置了一个失败场景,任务被救援后,最终统计显示failed=0 ... rescued=1。我希望failed计数器也能增加。此前我曾使用ignore_errors: true标记失败任务为已忽略,后来改用更规范的block/rescue/always,也曾在变量和block中使用过any_errors_fatal。
解决方案
要让rescue执行后仍将任务标记为失败并计入failed计数器,有两种实用方法:
方法一:在rescue末尾主动触发失败
在rescue块中完成必要操作(比如设置flag)后,添加fail模块强制标记任务失败,这样Ansible会将该block统计为失败:
- name: run command based on condition block: - name: run command based on condition command: *some curl command* when: *condition* register: out failed_when: 'rc != 0' debug: var=out rescue: - name: Set flag set_fact: flag="failed" when: "'FAILED' in out" - name: Mark block as failed fail: msg: "Block execution failed and was rescued" when: "'FAILED' in out"
执行后统计结果会同时显示failed=1和rescued=1,满足失败计数需求。
方法二:通过block注册结果控制失败状态
注册block的执行结果,利用failed_when判断rescue是否触发,从而将整个block标记为失败:
- name: run command based on condition block: - name: run command based on condition command: *some curl command* when: *condition* register: out failed_when: 'rc != 0' debug: var=out rescue: - name: Set flag set_fact: flag="failed" when: "'FAILED' in out" register: block_result failed_when: block_result.rescued
这里通过block_result.rescued判断rescue是否执行,只要触发救援就将block标记为失败,进而让failed计数器增加。
注意事项
- 若block中的任务因
when条件不满足被跳过,两种方法都不会触发rescue,也不会计入failed,符合预期逻辑。 - 方法一中的
fail模块可根据需求自定义错误信息,或结合变量动态输出。
内容的提问来源于stack exchange,提问作者Cruceru Malin
相关产品推荐
相关产品推荐

