Ansible PlayBook - Handler

> Infrastructure as code > Ansible

1 - About

Handler are task that are defined globally outside a play and can be called by the notify property in case of state change during task execution.

  • Handlers by default get executed
    • at the end of the playbook.
    • only when the task has the changed status
  • A handler would be called only once no matter how many times it was notified.
Advertising

3 - Syntax

  • Handler names and listen topics live in a global namespace.
  • If two handler tasks have the same name, only one will run.

You cannot notify a handler that is defined inside of an include. As of Ansible 2.1, this does work, however the include must be static.

4 - Execution

  • The notify keyword add an handler to a set of handler (ie an handler is run only once by section)
  • The set is flushed (processed) by default at the end of a section
  • The executions occurs in the order defined in the handlers section (handlers are always run in the same order they are defined, not in the order listed in the notify-statement.)

Handlers notified within:

  • pre_tasks, tasks, and post_tasks sections are automatically flushed in the end of section where they were notified;
  • roles section are automatically flushed in the end of tasks section, but before any tasks handlers.

If you ever want to flush all the handler commands immediately you can do this:

tasks:
   - shell: some tasks go here
   - meta: flush_handlers
   - shell: some other tasks

In the above example any queued up handlers would be processed early when the meta statement was reached.

Advertising

5 - Example

If the file template.j2 has changed, the memcached and apache services will be restarted.

handlers.yml
# handlers definition
handlers:
  - name: restart memcached
    service:
      name: memcached
      state: restarted
    listen: "restart web services" # group handlers in one call
  - name: restart apache
    service:
      name: apache
      state: restarted
    listen: "restart web services" 
 
# Or you can call the handlers one by one
---
- hosts: webservers
  remote_user: root
  - name: template configuration file
    template:
      src: template.j2
      dest: /etc/foo.conf
    notify:
       - restart memcached
       - restart apache
 
# Or you can call the handlers in one call
tasks:
    - name: restart everything
      command: echo "this task will restart the web services"
      notify: "restart web services"