Task includes with loops

Task inclusions can be combined with loops as well. When adding a loop instance to a task inclusion (or a with_ loop if using a version of Ansible earlier than 2.5), the tasks inside the file will be executed with the item variable, which holds the place of the current loop's value. The entire include file will be executed repeatedly until the loop runs out of items. Let's update our example play to demonstrate this:

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

tasks:
- include: more-tasks.yaml
loop:
- one
- two

We also need to update our more-tasks.yaml file to make use of the loop item:

--- 
- name: included task 1 
  debug: 
    msg: "I am the first included task with {{ item }}"  
- name: included task 2 
  debug: 
    msg: "I am the second included task with {{ item }}" 

When executed, we can tell that tasks 1 and 2 are executed a single time for each item in the loop:

Looping on inclusion is a powerful concept, but it does introduce one problem. What if there were tasks inside the included file that have their own loops? There will be a collision of the item variable, creating unexpected outcomes. For this reason, the loop_control feature was added to Ansible in version 2.1. Among other things, this feature provides a method to name the variable used for the loop, instead of the default of item. Using this, we can distinguish between the item instance that comes outside the inclusion from any item variables used inside the include. To demonstrate this, we'll add a loop_var loop control to our outer include:

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

tasks:
- include: more-tasks.yaml
loop:
- one
- two
loop_control:
loop_var: include_item

Inside more-tasks.yaml, we'll have a task with its own loop, making use of include_item and the local item:

--- 
- name: included task 1 
  debug: 
    msg: "I combine {{ item }} and {{ include_item }}" 
  with_items: 
    - a 
    - b 

When executed, we see that task 1 is executed twice per inclusion loop and that the two loop variables are used:

Other loop controls exist as well, such as label, which will define what is shown on the screen in the task output for the item value (useful for preventing large data structures from cluttering the screen) and pause, providing the ability to pause for a defined number of seconds between each loop.

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

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