如何编写具有多个任务的Ansible处理程序?

时间:2015-07-24 20:10:08

标签: handler ansible

为了响应更改,我有多个应该运行的相关任务。 如何编写具有多个任务的Ansible处理程序?

例如,我想要一个仅在已经启动的情况下重启服务的处理程序:

- name: Restart conditionally
  shell: check_is_started.sh
  register: result

- name: Restart conditionally step 2
  service: name=service state=restarted
  when: result

3 个答案:

答案 0 :(得分:57)

从Ansible 2.2开始,这个问题已得到妥善解决。

处理程序还可以“监听”通用主题,任务可以按如下方式通知这些主题:

handlers:
    - name: restart memcached
      service: name=memcached state=restarted
      listen: "restart web services"
    - name: restart apache
      service: name=apache state=restarted
      listen: "restart web services"

tasks:
    - name: restart everything
      command: echo "this task will restart the web services"
      notify: "restart web services"

此用法可以更轻松地触发多个处理程序。它还将处理程序与其名称分离,使得在剧本和角色之间共享处理程序变得更加容易

特别针对这个问题,这应该有效:

- name: Check if restarted
  shell: check_is_started.sh
  register: result
  listen: Restart processes

- name: Restart conditionally step 2
  service: name=service state=restarted
  when: result
  listen: Restart processes

并在任务中,通过“重启进程”

通知处理程序

http://docs.ansible.com/ansible/playbooks_intro.html#handlers-running-operations-on-change

答案 1 :(得分:50)

在处理程序文件中,使用notify将不同的步骤链接在一起。

- name: Restart conditionally
  debug: msg=Step1
  changed_when: True
  notify: Restart conditionally step 2

- name: Restart conditionally step 2
  debug: msg=Step2
  changed_when: True
  notify: Restart conditionally step 3

- name: Restart conditionally step 3
  debug: msg=Step3

然后从notify: Restart conditionally的任务中引用它。

请注意,您只能通知当前处理程序以下的处理程序。例如,Restart conditionally step 2无法通知Restart conditionally

来源:irc.freenode.net上的#ansible。我不确定这是否会在将来继续有效,因为官方文档中没有提到它。

答案 2 :(得分:24)

从Ansible 2.0开始,您可以在处理程序中使用include操作来运行多个任务。

例如,将您的任务放在单独的文件restart_tasks.yml中(如果您使用的角色将进入任务子目录,不是在handlers子目录中):

- name: Restart conditionally step 1
  shell: check_is_started.sh
  register: result

- name: Restart conditionally step 2
  service: name=service state=restarted
  when: result

您的处理程序将只是:

- name: Restart conditionally
  include: restart_tasks.yml

来源:在github上发布帖子:https://github.com/ansible/ansible/issues/14270

相关问题