Ansible loops

We can loop for repetitive operations using with_itemsLet us see an example where we parse the list and print the values:

---
- hosts : all
vars:
- test: Server
tasks:
- debug:
msg: "{{ test }} {{ item }}"
with_items: [ 0, 2, 4, 6, 8, 10 ]

The output of the playbook execution using the preceding code:

As we can see in the preceding screenshot, the iteration prints the value of Server plus the item value in the list for each item in the list. Similarly, for an integer iteration we can perform a loop using the with_sequence command:

---
- hosts : all
vars:
- test: Server
tasks:
- debug:
msg: "{{ test }} {{ item }}"
with_sequence: count=10

Additionally, let us say we want to print values skipping 2 (even numbers from 0 to 10), the same with_sequence command will be written as:

with_sequence: start=0 end=10 stride=2

Sometimes, we also need to pick any random value for performing specific task. The following sample code picks a random value from the 4 options available (in our case, Choice Random 1 till Choice Random 4) and displays it using msg variable:

---
- hosts : all
vars:
- test: Server
tasks:
- debug:
msg: "{{ test }} {{ item }}"
with_random_choice:
- "Choice Random 1"
- "Choice Random 2"
- "Choice Random 3"
- "Choice Random 4"

This will pick any random value from the list from the given options under the with_random_choice declaration.

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

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