Ansible running multiple handlers subtelty

In ansible, to run multiple handlers for a task you can chain handlers by notify dependencies, like in this stackoverflow answer. There is a small subtelty here. Notify action is triggered only if task was changed. Some tasks do not change at all(like debug: msg=...), some tasks do not always change. To run all required handlers surely you should set changed_when: True for all of them except the last one:

  # At first check if nginx config is correct
  - name: restart nginx
    shell: nginx -t
    changed_when: True
    notify: restart nginx step 2

  - name: restart nginx step 2
    service: name=nginx state=restarted

UPD: Since Ansible 2.3, named block could be more elegant solution. Unfortunately, blocks do not work in handlers: ansible #36480.

UPD2: Task may have multiple handlers like this:

- template: src=foo.j2 dest=/etc/foo
    - restart foo
    - restart bar

But be careful: handlers will always run in order they are defined, not in order they are listed in notify:

UPD3: Since Ansible 2.2, handlers can “listen” to some topic:

    - name: restart memcached
      service: name=memcached state=restarted
      listen: "restart web services"
    - name: restart apache
      service: name=apache state=restarted
      listen: "restart web services"
    - command: echo "this task will restart the web services"
      notify: "restart web services"

License: This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License Share: share on reddit share on hacker news share on facebook share on twitter share on linkedin share on slashdot