Lesson 14 / 26

Handlers: Act Only on Change

Use notify and handlers to restart or reload services only when a configuration actually changed.

Restart only when needed

A handler is a task that runs only when another task notifies it, and only if that task reported changed. Handlers run once at the end of the play, even if notified many times. This is the standard way to reload a service after a config change without restarting it needlessly on every run.

The handler in action

Look back at the first and second runs of site.yml. In the first run the template changed, so Reload app ran for each host. In the second run nothing changed, so the handler did not run at all. Real handlers would call ansible.builtin.service or systemd instead of debug.

  tasks:
    - name: Deploy nginx config
      ansible.builtin.template:
        src: nginx.conf.j2
        dest: /etc/nginx/nginx.conf
      notify: Reload nginx

  handlers:
    - name: Reload nginx
      ansible.builtin.service:
        name: nginx
        state: reloaded

Flush when order matters

If a later task needs the service reloaded first, add - meta: flush_handlers to run pending handlers at that point instead of waiting for the end.

Quick check: When does a handler run?

  • Never
  • On every run, always
  • Before the first task
  • When notified by a task that reported changed
Answer

When notified by a task that reported changed — Handlers fire only on change, once at the end of the play.