3

考虑以下 Ansible 任务:

- name: stop tomcat
  gather_facts: false
  hosts: pod1
  pre_tasks:
  - include_vars:
      dir: "vars/{{ environment }}"
  vars:
    hipchat_message: "stop tomcat pod1 done."
    hipchat_notify: "yes"
  tasks:
    - include: tasks/stopTomcat8AndClearCache.yml
    - include: tasks/stopHttpd.yml
    - include: tasks/hipchatNotification.yml

这会在 n 台服务器上停止 tomcat。我想要它做的是在它完成后发送一个 hipchat 通知。但是,此代码为任务发生的每个服务器发送单独的 hipchat 消息。这会使 hipchat 窗口充满冗余消息。在所有目标上完成 stop tomcat/stop httpd 任务后,有没有办法让 hipchat 任务发生一次?我希望任务关闭所有服务器上的 tomcat,然后发送一条时髦的聊天消息,说“tomcat 在 pod 1 上停止”。

4

2 回答 2

1

您可以有条件地仅在其中一个 pod1 主机上运行 hipchat 通知任务。

- include: tasks/hipChatNotification.yml
  when: inventory_hostname == groups.pod1[0]

或者,如果您不需要上一场比赛中的任何变量,您只能在 localhost 上运行它。

- name: Run notification
  gather_facts: false
  hosts: localhost
  tasks:
  - include: tasks/hipchatNotification.yml

您还可以在任务本身上使用run_once标志。

- name: Do a thing on the first host in a group.
  debug: 
    msg: "Yay only prints once"
  run_once: true

- name: Run this block only once per host group
  block:
  - name: Do a thing on the first host in a group.
    debug: 
      msg: "Yay only prints once"
  run_once: true
于 2019-04-02T18:53:23.940 回答
0

Ansible 处理程序是针对此类问题制作的,您希望在操作结束时运行一次任务,即使它可能已在播放中多次触发。

您可以在 playbook 中定义一个处理程序部分并在任务中通知它,除非有任务通知,否则处理程序将不会运行,并且无论通知多少次都只会运行一次。

handlers:
    - name: hipchat notify
      hipchat:
        room: someroom
        msg: tomcat stopped on pod 1

在您的播放任务中,只需在应该触发处理程序的任务上包含一个“通知”,如果它们发生更改,它将在所有任务执行后运行处理程序。

- name: Stop service httpd, if started
  service:
    name: httpd
    state: stopped
  notify: 
    - hipchat notify
于 2019-04-03T18:31:49.617 回答