【问题标题】:How to run an ansible task only once regardless of how many targets there are无论有多少目标,如何只运行一次 ansible 任务
【发布时间】:2019-04-02 18:41:28
【问题描述】:

考虑以下 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 上停止”。

【问题讨论】:

  • run_once: true 可能是你的朋友,但它(据我记得)不能用于包含。我不认为你的 hipchat yml 有这么多任务。您可能可以在那里使用它。

标签: ansible hipchat


【解决方案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

【讨论】:

  • 我试图避免这样做,以免使剧本膨胀。我有一个很长的剧本来自动化冗长的部署过程。我想我可以在一个游戏之后放一个游戏来通知前一个游戏成功,但这似乎太冗长了。我不想以第一种方式执行此操作 - 有条件地在一个主机上执行 - 因为在该部分中的所有主机都完成之前,该步骤不会被视为已完成。
  • 您可能想查看包含任务中的 run_once 标志。您也可以尝试对一组任务执行此操作。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-19
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多