Two ways to run multiple Ansible handlers

How to execute two Ansible handlers on a changed status of Ansible Playbook.

What is an Ansible handler?

> Handler runs tasks on change.

Handlers execute some tasks only when the previous task returns a changed status. If not necessary, they don't execute.

Links

  • https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_handlers.html

Demo

Let's jump into two real-life examples of how to run multiple Ansible handlers.

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

Let's suppose we would like to execute two handlers on the screen, for example, two messages on the screen.

Solution 1

code

  • two-1.yml

``yaml

---

  • name: handler Playbook

hosts: all

tasks:

- name: Test connection

ansible.builtin.command: "uptime"

notify: message

handlers:

- name: message 1

ansible.builtin.debug:

msg: message 1

listen: message

- name: message 2

ansible.builtin.debug:

msg: message 2

listen: message

`

  • inventory

`bash

localhost ansible_connection=local

`

execution

`bash

$ ansible-playbook -i inventory two-1.yml

PLAY [handler Playbook] *

TASK [Gathering Facts]

ok: [localhost]

TASK [Test connection]

changed: [localhost]

RUNNING HANDLER [message 1] *

ok: [localhost] => {

"msg": "message 1"

}

RUNNING HANDLER [message 2] *

ok: [localhost] => {

"msg": "message 2"

}

PLAY RECAP **

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

`

Solution 2

code

  • two-2.yml

`yaml

---

  • name: handler Playbook

hosts: all

tasks:

- name: Test connection

ansible.builtin.command: "uptime"

notify:

- message 1

- message 2

handlers:

- name: message 1

ansible.builtin.debug:

msg: message 1

- name: message 2

ansible.builtin.debug:

msg: message 2

`

execution

``bash

$ ansible-playbook -i inventory two-1.yml

PLAY [handler Playbook] *

TASK [Gathering Facts]

ok: [localhost]

TASK [Test connection]

changed: [localhost]

RUNNING HANDLER [message 1] *

ok: [localhost] => {

"msg": "message 1"

}

RUNNING HAND