Conditional task includes

Similar to passing data into included files, conditionals can also be passed into included files. This is accomplished by attaching a when statement to the include operator. This conditional does not cause Ansible to evaluate the test to determine whether the file should be included; rather, it instructs Ansible to add the conditional to each and every task within the included file (and any other files the said file may include).

It is not possible to conditionally include a file. Files will always be included; however, a task conditional can be applied to every task within.

Let's demonstrate this by modifying our first example that includes simple debug statements. We'll add a conditional and pass along some data for the conditional to use. First, let's modify the includer.yaml playbook:

---
- name: task inclusion
hosts: localhost
gather_facts: false

tasks:
- include: more-tasks.yaml
when: item | bool
vars:
a_list:
- true
- false

Next, let's modify more-tasks.yaml to loop over the a_list variable in each task:

---
- name: included task 1
debug:
msg: "I am the first included task"
with_items: "{{ a_list }}"

- name: include task 2
debug:
msg: "I am the second included task"
with_items: "{{ a_list }}"

 

Now let's run the playbook and see our new output:

We can see a skipped iteration per task, the iteration where the item evaluated to a Boolean false. It's important to remember that all hosts will evaluate all included tasks. There is no way to influence Ansible to not include a file for a subset of hosts. At most, a conditional can be applied to every task within an include hierarchy so that included tasks may be skipped. One method to include tasks based on host facts is to utilize the group_by action plugin to create dynamic groups based on host facts. Then, you can give the groups their own plays to include specific tasks. This is an exercise left up to the reader.

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

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