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

查看:27
本文介绍了如何编写具有多个任务的 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天全站免登陆