如何编写具有多个任务的Ansible处理程序? [英] How do I write an Ansible handler with multiple tasks?

查看:57
本文介绍了如何编写具有多个任务的Ansible处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In response to a change, I have multiple related tasks that should run. How do I write an Ansible handler with multiple tasks?

例如,我希望处理程序仅在已经启动时重新启动服务:

For example, I would like a handler that restarts a service only if already started:

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

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

推荐答案

从Ansible 2.2开始,有适当的解决方案.

There is proper solution to this problem as of Ansible 2.2.

处理程序还可以侦听"一般主题,任务可以按以下方式通知这些主题:

handlers can also "listen" to generic topics, and tasks can notify those topics as follows:

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"

此用法使触发多个处理程序变得更加容易.它还使处理程序与其名称脱钩,从而使在剧本和角色之间共享处理程序更加容易

This use makes it much easier to trigger multiple handlers. It also decouples handlers from their names, making it easier to share handlers among playbooks and roles

专门针对这个问题,这应该可行:

Specifically to the question, this should work:

- 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

在任务中,通过重新启动进程"通知处理程序

and in the task, notify handlers via 'Restart processes'

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

这篇关于如何编写具有多个任务的Ansible处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆