任务的 Ansible 条件处理程序?

3

提醒一下,我正在以“拉模式”而不是推模式运行我的Ansible playbook。因此,我的节点将通过Hipchat发布其任务结果。

话虽如此,我有一个安装RPM的任务。当安装成功时,节点会通过Hipchat通知任务已成功运行。现在,如果任务失败,我会强制使用“--force-handlers”参数通知hipchat。我的问题是,是否有一种方法根据任务结果调用特定的处理程序?

任务

- name: Install Perl modules
  command: sudo rpm -Uvh {{ rpm_repository }}/{{ item.key }}-{{ item.value.svn_tag }}.rpm --force
  with_dict: deploy_modules_perl
  notify: announce_hipchat

处理程序

- name: announce_hipchat
  local_action: hipchat
        from="deployment"
        token={{ hipchat_auth_token }}
        room={{ hipchat_room }}
        msg="[{{ ansible_hostname }}] Successfully installed RPMs!"
        validate_certs="no"

1
你可以在你的处理程序中使用'when'、'with_items'等。条件语句是否能给你想要的结果?根据你的解释和示例代码,我不太确定你想要做什么... - Bruce P
这篇文档的这一部分可能会有所帮助:https://docs.ansible.com/playbooks_error_handling.html#ignoring-failed-commands。您可以忽略失败,然后根据它是失败还是成功来执行不同的操作。 - David
1个回答

2
在这种情况下,我使用多个处理程序。请参见以下示例:

文件 site.yml

- hosts: all
  gather_facts: false
  force_handlers: true
  vars:
  - cmds:
      echo: hello
      eccho: hello
  tasks:
  - name: echo
    command: "{{ item.key }} {{ item.value }}"
    register: command_result
    with_dict: "{{ cmds }}"
    changed_when: true
    failed_when: false
    notify:
    - "hipchat"
  handlers:
  - name: "hipchat"
    command: "/bin/true"
    notify:
    - "hipchat_succeeded"
    - "hipchat_failed"
  - name: "hipchat_succeeded"
    debug:
      var: "{{ item }}"
    with_items: "{{ command_result.results | selectattr('rc', 'equalto', 0) | list }}"
  - name: "hipchat_failed"
    debug:
      var: "{{ item }}"
    with_items: "{{ command_result.results | rejectattr('rc', 'equalto', 0) | list }}"

使用命令

ansible-playbook -c local -i "localhost," site.yml

注意:使用测试过滤器'equalsto'需要在jinja2 2.8及以上版本中添加。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接