Ansible: Handlers

What is a Handler?

A handler in Ansible is a special task that runs only when it’s notified by another task. Handlers are commonly used for actions like restarting services whenever a configuration file changes.

Example:
Handler is “restart apache”, so whenever you change the Apache config, you can notify this handler to restart Apache.


How to Create a Handler

You define handlers in your playbook like this:

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

How to Notify a Handler

In your regular task (for example, updating Apache config), add the notify keyword to tell Ansible when to trigger a handler:

- name: Copy Apache config
  copy:
    src: new_apache.conf
    dest: /etc/apache2/sites-available/000-default.conf
  notify: restart apache   # This line tells Ansible to run the handler when the file changes

Full Example Together

Here’s a basic playbook that defines a handler, then uses a task to notify it:

- name: Apache config with handler example
  hosts: webservers
  become: yes

  tasks:
    - name: Copy Apache config
      copy:
        src: new_apache.conf
        dest: /etc/apache2/sites-available/000-default.conf
      notify: restart apache

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

Summary:

  • Handler is any task you want to run later (like restarting a service).
  • handlers section: Define the handler
  • notify: keyword: Used in a task to trigger the handler if there’s a change

That’s how you define and use handlers—simple, step-by-step!