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

How to catch errors in handlers in Ansible?

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

这是我的剧本,我希望 Rescue when handler fails 任务到 运行:

- 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

如何从这个 failing handler 和 运行 一些清理任务中捕获失败?

郑重声明,上述方法无效,因为您的处理程序收到通知的时间和它有效 运行 的时间完全不同。您需要在处理程序 运行 时捕获故障,而不是在它被通知时捕获。

我会走那条路。

将您的处理程序任务放入文件中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

默认情况下,处理程序 运行 在部分末尾(pre_taskstasks 等),从那里通知他们。但是,可以通过使用 meta action- meta: flush_handlers.

在任务后立即触发处理程序

使用这种技术,我们可以在 Print a message 任务之后立即触发处理程序。然后 playbook 可以继续执行下一个任务。

例如:

  tasks:
    - name: Print a message
      debug:
        msg: i execute normally
      changed_when: true
      notify: failing handler

    - meta: flush_handlers

    - name: rescue when handler fails
      debug:
        msg: rescue
      when: _handler_status | default({}) is failed

  handlers:
    - name:  failing handler
      command: /bin/false
      register: _handler_status
      ignore_errors: true

正如@Zeitounator 正确指出的那样,刷新处理程序对于上面只有 1 个通知任务的示例没有问题。然而,当其他任务有机会通知其他处理程序时,这可能是不受欢迎的。在这种情况下,任务可以放在 post_tasks 部分下。如下所示:

  tasks:
    - name: Print a message
      debug:
        msg: i execute normally
      changed_when: true
      notify: failing handler

  post_tasks:
    - name: rescue when failing handler fails
      debug:
        msg: rescue
      when: _handler_status | default({}) is failed

  handlers:
    - name:  failing handler
      command: /bin/false
      register: _handler_status
      ignore_errors: true