Handler

  • Handlers are tasks that respond to a notification triggered by other tasks.

  • Tasks only notify their handlers when the task changes something on a managed host.

  • Each handler has a globally unique name and is triggered at the end of a block of tasks in a playbook.

  • If not task notifies the handler by name then the handler will not run.

  • If one or more tasks notify the handler, the handler will run exactly once after all other tasks in the play have completed.

  • Because handlers are tasks, administrators can use the same modules in handlers that they would use for any other task.

  • Normally, handlers are used to reboot hosts and restart services.

  • Handlers can be considered as inactive tasks that only get triggered when explicitly invoked using a notify statement.

  • Handlers always run in the order specified by the handlers section of the play. They do not run in the order in which they are listed by notify statements in a task, or in the order in which tasks notify them.

  • Handlers normally run after all other tasks in the play complete. A handler called by a task in the tasks part of the playbook will not run until all tasks under tasks have been processed.

  • Handler names exist in a per-play namespace. If two handlers are incorrectly given the same name, only one will run.

  • Even if more than on task notifies a handler, the handler only runs once. If no tasks notify it, a handler will not run.

  • If a task that includes a notify statement does not report a changed result (for example, a package is already installed and the task reports ok), the handler is not notified. The handler is skipped unless another task notifies it. Ansible notifies handlers only if the task reports the changed status.

Example

One Handler

tasks:
  - name: copy demo.conf configuration template
    template:
      src: /var/lib/templates/demo.conf.template
      dest: /etc/httpd/conf.d/demo.conf
    notify:
      - restart apache

handlers:
  - name: restart apache
    service:
      name: httpd
      state: restarted

Multiple Handlers

Last updated