Standard loops

Standard loops in playbook are often used to easily perform similar tasks multiple times. The syntax for standard loops is very easy; the variable {{ item }} is the placeholder looping over the with_items list. For example, take a look at the following:

      tasks:
- name: echo loop items
command: echo {{ item }}
with_items: ['r1', 'r2', 'r3', 'r4', 'r5']

It will loop over the five list items with the same echo command:

TASK [echo loop items] *********************************************************
changed: [192.168.199.185] => (item=r1)
changed: [192.168.199.185] => (item=r2)
changed: [192.168.199.185] => (item=r3)
changed: [192.168.199.185] => (item=r4)
changed: [192.168.199.185] => (item=r5)

Combining with network command module, the following task will add multiple vlans to the device:

 tasks:
- name: add vlans
eos_config:
lines:
- vlan {{ item }}
provider: "{{ cli }}"
with_items:
- 100
- 200
- 300

The with_items list can also be read from a variable, which gives greater flexibility to the structure of your playbook:

vars:
vlan_numbers: [100, 200, 300]
<skip>
tasks:
- name: add vlans
eos_config:
lines:
- vlan {{ item }}
provider: "{{ cli }}"
with_items: "{{ vlan_numbers }}"

The standard loop is a great time saver when it comes to performing redundant tasks in a playbook. In the next section, we will take a look at looping over dictionaries.

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

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