Hi,
Is there a way to loop over an array in ansible with a given array size. eg: I have an array with 10 elements. I want to limit the iteration only to first 5 elemets.
Thanks.
Hi,
Is there a way to loop over an array in ansible with a given array size. eg: I have an array with 10 elements. I want to limit the iteration only to first 5 elemets.
Thanks.
the slice() filter will give you a list of arrays each with one element in it
(i.e., not what you were expecting, but still useful).
Could you use an “indexed array” and use when to check for index <= 5?
https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html#with-indexed-items
- name: with_indexed_items
debug:
msg: "Index {{ item.0 }} - Value {{ item.1 }}"
with_indexed_items: "{{ items }}"
- name: with_indexed_items -> loop
debug:
msg: "{{ index }} - {{ item }}"
loop: "{{ items|flatten(levels=1) }}"
loop_control:
index_var: index
name: loop over first 5
debug: var=item
loop: "{{ mylist[:5] }}"
@Brain Coca
That looks nice. Btw what if the number of elements available in the array is less than 5 and we give loop: “{{ mylist[:5] }}”. Should that throw any exception?
No, it will consume UP TO that number
Thanks. I tried it out as well. In addition this degit no ‘5’ will be an input from --extra-vars. eg : --extra-vars ‘size=5’
then i was trying to consume that variable like this loop: “{{ mylist[:size] }}” But this throws an error saying ‘’ slice indices must be integers or none or have an init method. is there a way that I can set this limit of the array using a variable?
cause size=5 is a string (k=v notation does not 'type' well),
mylist[:size|int] to avoid that or you can try yaml notation, but that
can also use type depending on circumstance, the |int at 'consumption'
is always safe.
UPDATE
a solution would be “{{size | int}}”. I think when we pass it as an optional it take it as a string by default so using ‘int’ filter would solve this.
Thanks ,
Madushan