ansible - 如何在 Ansible 中捕获处理程序中的错误?

标签 ansible

我的代码中的处理程序在某些情况下会失败,然后导致整个剧本运行崩溃,我想在处理程序中捕获这些失败并进行某种清理。

这是我的剧本,我希望在其中运行处理程序失败时的救援任务:

- 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/

相关文章:

pip - 如何在 MacOS Sierra 上使用 Brew 安装 Ansible 2.4.x

ansible - 如何在 ansible playbook 任务中运行 nohup 命令?

ansible - ansible 中的双 with_items 循环

python - 我如何确认 python 包是使用 ansible 安装的

Ansible:我可以使用保管库中加密的 ssh key 吗?

ansible - 在ansible中如何禁用单个任务的弃用警告?

ansible - 无论指向何处,如何检查符号链接(symbolic link)是否存在

shell - Ansible shell 和 with_items

dictionary - ansible with_dict 在提供 set_fact 变量时失败

Ansible 将 'setup' 输出与任务输出结合到 JSON