Including handlers

Handlers are essentially tasks. They're a set of potential tasks triggered by way of notifications from other tasks. As such, handler tasks can be included just as regular tasks can. The include operator is legal within the handlers block.

Unlike with task inclusions, variable data cannot be passed along when including handler tasks. However, it is possible to attach a conditional to a handler inclusion, to apply the conditional to every handler within the file.

Let's create an example to demonstrate this. First, we'll create a playbook that has a task that will always change, and that includes a handler task file and attaches a conditional to that inclusion:

--- 
- name: touch files 
  hosts: localhost 
  gather_facts: false 
 
  tasks:
- name: a task
debug:
msg: "I am a changing task"
changed_when: true
notify: a handler

handlers:
- include: handlers.yaml
when: foo | default('true') | bool
When evaluating a variable that may be defined outside a playbook, it's best to use the bool filter to ensure that strings are properly converted to their Boolean meaning.

Next, we'll create handlers.yaml to define our handler task:

---
- name: a handler
debug:
msg: "handling a thing"

 

If we execute this playbook without providing any further data, we should see our handler trigger:

Now let's run the playbook again; this time, we'll define foo as extra-var and set it to false in our ansible-playbook execution arguments:

This time, since foo evaluates to false, our included handler gets skipped.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.11.98