Ansible - Loop through a sequence of numbers using the with_sequence parameter
by
Jeremy Canfield |
Updated: July 06 2023
| Ansible articles
The following parameters can be used to loop through each item in an array / list.
- loop
- vars
- with_items
- with_indexed_items
- with_list
- with_nested
- with_sequence (this article)
The with_sequence parameter can be used to iterate over a sequence of numbers. In this example, the debug module is used iterate over a sequence of 0 through 10.
- name: sequence 0 to 3
debug:
msg: "{{ item }}"
with_sequence: start=0 end=3
Something like this should be returned.
TASK [sequence 0 to 3]
ok: [server1.example.com] => (item=0) => {
"msg": "0"
}
ok: [server1.example.com] => (item=1) => {
"msg": "1"
}
ok: [server1.example.com] => (item=2) => {
"msg": "2"
}
ok: [server1.example.com] => (item=3) => {
"msg": "3"
}
Or, perhaps a bit more practical example would be using the file module to create a sequence of files.
- name: create foo0.txt through foo3.txt
file:
path: /tmp/foo{{ item }}.txt
state: touch
with_sequence: start=0 end=3
The when parameter can be used as well.
- name: sequence 0 to 3
set_fact:
foo: "{{ item }}"
with_sequence: start=0 end=3
when: foo|int < 2
Did you find this article helpful?
If so, consider buying me a coffee over at