Loading...

Watch: Run Immediately an Ansible Handler - Ansible Playbook

How to flush the execution of an Ansible handler after the notification task using the ansible.builtin.meta module.

When do Ansible Handlers run?

> By default, handlers run after all the tasks in a particular play have been completed.

Links

  • https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_handlers.html#controlling-when-handlers-run

Demo

Let's jump into a real-life example of how to run an Ansible Handler immediately.

First of all, we need a task changed status. The simplest Ansible module returning a "changed" status is Ansible command module with a Linux command, like "uptime".

Let's suppose we would like to execute a handler immediately after the changed status and not wait for the next task using the ansible.builtin.meta module.

Initial Playbook

  • flush_before.yml

``yaml

---

  • name: handler Playbook

hosts: all

tasks:

- name: changed status

ansible.builtin.command: "uptime"

notify: message 1

- name: message 2

ansible.builtin.debug:

msg: message 2

handlers:

- name: message 1

ansible.builtin.debug:

msg: message 1

`

inventory

`ini

localhost ansible_connection=local

`

Initial Execution

As you can notice the message 1 handler is executed AFTER the last task (message 2) of the Play being executed.

`bash

$ ansible-playbook -i inventory flush_before.yml

PLAY [handler Playbook] *

TASK [Gathering Facts]

ok: [localhost]

TASK [changed status] *

changed: [localhost]

TASK [message 2] **

ok: [localhost] => {

"msg": "message 2"

}

RUNNING HANDLER [message 1] *

ok: [localhost] => {

"msg": "message 1"

}

PLAY RECAP **

localhost : ok=4 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

`

Modified Playbook

Let's add the ansible.builtin.meta Ansible module after the first task.

``yaml

---

  • name: handler Playbook

hosts: all

tasks:

- name: changed status

ansible.builtin.command: "uptime"

notify: message 1

- name: flush

ansible.builtin.meta: flush_handlers

- name: message 2

ansible.builtin.debug:

msg: message 2

handlers:

- name: messag

Read the full tutorial: Run Immediately an Ansible Handler - Ansible Playbook