I would like to achieve something like this with ansible
- debug:
msg: "{{ item }}"
with_items:
- "0"
- "1"
But to be generated from a range(2) instead of having hardcoded the iterations. How would yo do that?
item is not a command, but a variable automatically created and populated by Ansible in tasks which use loops. In the following example: - debug: msg: "{{ item }}" with_items: - first - second. the task will be run twice: first time with the variable item set to first , the second time with second .
Nested loops in many ways are similar in nature to a set of arrays that would be iterated over using the with_nested operator. Nested loops provide us with a succinct way of iterating over multiple lists within a single task. Now we can create nested loops using with_nested.
Defining inner and outer variable names with loop_var However, by default Ansible sets the loop variable item for each loop. This means the inner, nested loop will overwrite the value of item from the outer loop. You can specify the name of the variable for each loop using loop_var with loop_control .
To create a conditional based on a registered variable: Register the outcome of the earlier task as a variable. Create a conditional test based on the registered variable.
- debug:
var: item
with_sequence: 0-1
or
with_sequence: start=0 end=1
or
with_sequence: start=0 count=2
Pay attention that sequences are string values, not integers (you can cast with item|int
)
Reference: Looping over Integer Sequences
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With