Table of Contents

What are Handlers in Ansible? And how to use them with examples.

About

Handlers 1) are tasks that are:

They are mostly used to restart, reload, and test that services are up and running.

Example

Playbook form

This example shows you a playbook.

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

# 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" 

# Playbook
---
- hosts: webservers
  remote_user: root
  - name: template configuration file
    template:
      src: template.j2
      dest: /etc/foo.conf
    notify: # Call the handlers one by one
       - restart memcached
       - restart apache

tasks:
    - name: restart everything
      command: echo "this task will restart the web services"
      notify: "restart web services" # Call the handlers in one call

Role form

This example shows you handlers in a role.

The handlers are generally in the roleName\handlers\main.yml file:

# a single
- name: 'prometheus reload'
  become: yes
  systemd:
    name: 'prometheus.service'
    enabled: 'yes'
    daemon_reload: yes
    state: restarted

# multiple, as of version 2.8, you need to use include_tasks (not block or import_tasks)
- name: 'prom-node-exporter restart'
  include_tasks: handlers/node_exporter_handlers.yml

Syntax

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.

Execution

Handlers notified within:

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.

Support

Interactive authentication required

Unable to restart service postfix: Failed to restart postfix.service: Interactive authentication required.
See system logs and 'systemctl status postfix.service' for details.

Handler are run with the connected user privilege if you want to perform action that requires root privilege, you should become root.

Example:

- name: restart postfix
  service: name=postfix state=restarted
  become: true

How to resolve: The requested handler was not found

Possible resolution: