Repeat N times for each element of the list in Ansible
It’s the usual ‘suck at iterations’ problem in Ansible.
My problem:
mytasks:
- name: foo
repeat: 10
- name: bar
repeat: 99
I need to create foo-0, foo-1, …, foo-9, bar-0, bar-1,…, bar-99 in a single loop in Ansible.
The ugly solution with subelements will be like this:
- name: Generating tasks
debug:
msg: "{{ item.0.name }}-{{ item.1 }}"
loop: "{{ mytasks | subelements('ids') }}"
To make it works (I changed ‘repeat’ to ids) we need to alter mytasks:
mytasks:
- name: foo
ids: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Don’t ask me to write bar with ids from 0 to 99. I hate it.
I tried to invent crazy wheels with range filter for subelements for ‘repeat’, and I couldn’t.
Alexander, my colleague, found an elegant solution which really I love:
mytasks:
- name: foo
ids: "{{ range(0, 10) }}"
- name: bar
ids: "{{ range(0, 99) }}"
And it works with a task shown above. And you don’t need to enumerate all integers. Beautiful!