我的代码中的处理程序在某些情况下会失败,然后导致整个剧本运行崩溃,我想在处理程序中捕获这些失败并进行某种清理。
这是我的剧本,我希望在其中运行处理程序失败时的救援
任务:
- hosts: localhost
tasks:
- name: something something
block:
- name: Print a message
debug: msg='I execute normally'
changed_when: yes
notify: failing handler
rescue:
- name: Rescue when handler fails
debug:
msg: 'Rescue'
handlers:
- name: failing handler
command: /bin/false
如何从这个失败处理程序捕获失败并运行一些任务进行清理?
最佳答案
郑重声明,上述方法不起作用,因为处理程序收到通知的时间和有效运行的时间完全不同。您需要在处理程序运行时捕获失败,而不是在收到通知时捕获失败。
我会走那条路。
将处理程序任务放入文件 my_failing_handler.yaml
- block:
- name: the task that might fail
command: /bin/false
rescue:
- name: rescue when handler fails
debug:
msg: "rescue"
然后在你的主要剧本中:
- hosts: localhost
tasks:
- name: Print a message
debug: msg='I execute normally'
changed_when: yes
notify: failing handler
handlers:
- name: failing handler
include_tasks: my_failing_handler.yaml
关于ansible - 如何在 Ansible 中捕获处理程序中的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71665568/