ruk·si

⚙️ Ansible
Handlers

Updated at 2017-03-22 01:46

Tasks may have any number of notifys. These ‘notify’ actions are triggered at the end of each block of tasks in a play (e.g. pre_tasks, tasks, post_tasks or block), and will only be triggered once even if notified by multiple different tasks.

---
- hosts: webserver
  tasks:
    - name: create configuration file
      template: src=template.j2 dest=/etc/foo.conf
      notify:
         - restart memcached
         - restart apache
  handlers:
    - name: restart memcached
      service: name=memcached state=restarted
    - name: restart apache
      service: name=apache state=restarted

As of Ansible 2.2, handlers can also listen to generic topics.

---
- hosts: webserver
  tasks:
      - name: restart everything
        command: echo "this task will restart the web services"
        notify: restart web services
  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

Notify handlers are always run in the same order they are defined, not in the order listed in the notify-statement.

Handler names and listen topics live in a global namespace so don't make their names too generic. If two handler tasks have the same name, only one will run.

You cannot notify a handler that is defined inside of an include. Except if the include is static.

You can force activate handlers with meta: flush_handlers.

- hosts: webserver
  tasks:
    - ping:
    - meta: flush_handlers
    - ping:

Sources