Ansible - 发送有关成功和失败任务的通知

时间:2018-06-04 08:11:48

标签: ansible

我一直在阅读和测试块模块以进行错误处理,并借助以下问题Ansible: execute task (or handler) if any task failed确实有助于理解这种情况。 现在,我想要完成的是获得成功任务的通知。 所以最终,我会收到有关成功和失败任务的通知。 如果不将每个任务放在专用块模块中,如何实现,我也想过使用 include_tasks 并循环执行任务,但我不确定这是否正确,而且任务必须是按特定顺序执行。

那么如何以一种每个任务既有救援任务又通知成功的方式正确编写呢? 另外,如何将任务名称及其输出作为消息传递给处理程序?

处理失败任务的伪代码:

--- # Event Handling
- hosts:         localhost  
  connection:    local
  gather_facts:  no

  tasks:
    - name: Installing packages
      block:
        - command1
        - command2
        - command3
          notify: Success Handler
      rescue:
        - name: Sending alerts
          notify: Failed task

 handlers: 
   - name: Success Handler
     debug: 
       msg: "task {{ task_id$ }} was success"
   - name: Failed task
     debug:
       msg: "task {{ task_id$ }} failed, the error was {{ task_id: failed results }}""

提前致谢。

1 个答案:

答案 0 :(得分:0)

你几乎给出了解决方案。为什么不创建导入手册甚至角色并按顺序使用{{with_items}}传递命令?

像:

  - name: Run My Tasks Role
    include_role:
      name: tasksandnotification
    vars:
      taskvalue: "{{ item }}"
    with_items:
      - task1
      - task2

然后在角色/ tasks / main.yml

- name: Installing packages
      block:
        - "{{ taskvalue }}"
          notify: Success Handler
      rescue:
        - name: Sending alerts
          notify: Failed task

和role / handlers / main.yml

   - name: Success Handler
     debug: 
       msg: "task {{ taskvalue }} was success"
   - name: Failed task
     debug:
       msg: "task {{ taskvalue }} failed, the error was {{ taskvalue: failed results }}"

我还没有完全测试,但这是我脑子里的想法。