TExcelTAD

Handlers

A config file changed, so the service must reload. But only if it changed: reloading nginx on every run of a playbook that runs every 30 minutes would drop connections for nothing. Handlers solve this. A task notifys a handler by name; the handler runs once, at the end of the play, and only if at least one notifying task reported changed.

yaml
tasks:
  - name: Nginx site config
    ansible.builtin.template:
      src: site.conf.j2
      dest: /etc/nginx/sites-available/app.conf
      validate: nginx -t -c %s        # never write a broken config
    notify: Reload nginx

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

service needs root and a running systemd, so here the handlers write to a log file instead, which shows exactly when they run:

bash · try it yourself
cat > web.yml <<'YML'
- name: Handlers demo
  hosts: localhost
  gather_facts: false
  vars:
    nginx_port: 8080
  tasks:
    - name: Site config
      ansible.builtin.copy:
        dest: site.conf
        content: "listen {{ nginx_port }};\n"
        mode: "0644"
      notify: Reload nginx

    - name: TLS config
      ansible.builtin.copy:
        dest: tls.conf
        content: "ssl_protocols TLSv1.3;\n"
        mode: "0644"
      notify: Reload nginx

    - name: A task after the notifications
      ansible.builtin.debug:
        msg: tasks finished

  handlers:
    - name: Reload nginx
      ansible.builtin.shell: echo "reload at port {{ nginx_port }}" >> reloads.log
      changed_when: true
YML
echo "=== first run: both files new"
ansible-playbook web.yml | grep -E '^(TASK|RUNNING|changed|ok)'
echo "=== second run: nothing changed"
ansible-playbook web.yml | grep -E '^(RUNNING|changed)'
echo "=== third run: the port changed"
ansible-playbook web.yml -e nginx_port=9090 | grep -E '^(RUNNING|changed)'
cat reloads.log
=== first run: both files new
TASK [Site config] *************************************************************
changed: [localhost]
TASK [TLS config] **************************************************************
changed: [localhost]
TASK [A task after the notifications] ******************************************
ok: [localhost] => {
RUNNING HANDLER [Reload nginx] *************************************************
changed: [localhost]
=== second run: nothing changed
=== third run: the port changed
changed: [localhost]
RUNNING HANDLER [Reload nginx] *************************************************
changed: [localhost]
reload at port 8080
reload at port 9090

(The variable is called nginx_port, not port: port is one of Ansible's reserved names, and ansible-core 2.21 warns when you define it. Variables lists the naming rules.)

Notice three things:

  1. Two tasks notified Reload nginx, yet it ran once.
  2. It ran after the last task, not right after the first notification.
  3. On the unchanged run it didn't run at all.

Rules worth knowing

Rule Detail
order handlers run in the order they are defined in handlers:, not the order notified
listen a handler can subscribe to a topic: listen: web config changed; several handlers can listen to one topic, and tasks notify the topic
meta: flush_handlers runs pending handlers now, e.g. restart the database before the migration task that needs it
failures if a later task fails, pending handlers don't run on that host, so the change is never applied; --force-handlers (or force_handlers: true in the play) runs them anyway
roles a role's handlers live in handlers/main.yml and can be notified from anywhere in the play

Flushing handlers mid-play

bash · try it yourself
cat > flush.yml <<'YML'
- name: Flush handlers before a dependent task
  hosts: localhost
  gather_facts: false
  tasks:
    - name: Database config
      ansible.builtin.copy:
        dest: db.conf
        content: "max_connections = 200\n"
        mode: "0644"
      notify: Restart database

    - name: Apply pending handlers now
      ansible.builtin.meta: flush_handlers

    - name: Migration (needs the restarted database)
      ansible.builtin.debug:
        msg: migrating

  handlers:
    - name: Restart database
      ansible.builtin.debug:
        msg: database restarted
      changed_when: true
YML
ansible-playbook flush.yml | grep -E '^(TASK|RUNNING)'
TASK [Database config] *********************************************************
TASK [Apply pending handlers now] **********************************************
RUNNING HANDLER [Restart database] *********************************************
TASK [Migration (needs the restarted database)] ********************************

Restart or reload?

reloaded re-reads the configuration without dropping connections (nginx, HAProxy, sshd, PostgreSQL for most settings); restarted stops and starts the process. Prefer reload in handlers for services that support it, and validate the file before writing it (validate: on template/copy), so the handler never reloads a broken config. The linux-admin systemctl lesson explains the difference on the service side.

Test yourself

Three tasks notify the same handler; two report changed, one ok. How often does the handler run?

  1. Three times
  2. Twice
  3. Once, at the end of the play
  4. Never

A handler is notified, then a later task fails on that host. What happens by default?

  1. The handler runs anyway
  2. The handler doesn't run on that host
  3. The play restarts
  4. Ansible reverts the change

How do you run pending handlers before a task that depends on them?

  1. notify: now
  2. ansible.builtin.meta: flush_handlers
  3. handlers: first
  4. Move the handler into tasks