Reputation: 377
I am having issue with an ansible with_sequence loop where the end is a variable that could be zero. I am looking for a way to skip the loop so I don't get the error "to count backwards make stride negative".
Simplified sample :
- name : Register zero as var
# The real command is something like "script | filter | wc -l"
shell: echo 0
register: countvar
# I want this loop to run only when countvar is > 0
- name: Do smthg with countvar
command: echo "{{ item }}"
with_sequence: start=1 end={{countvar.stdout|int}}
when: countvar.stdout|int >= 1
Upvotes: 4
Views: 11990
Reputation: 18411
My requirement was slightly different; I wanted to start the loop with index: 1
, but only if the ending index is > 0. Meaning I did not want to default the ending index to 1.
loop: "{{ query('sequence', 'start=1 end=' + countvar.stdout) if countvar.stdout|int > 0 else [] }}"
Here, the ending index will remain the same if countvar.stdout > 0
else supply empty list []
to the loop.
Upvotes: 0
Reputation: 11615
The when
condition is executed at each iteration on the loop, it cannot be used as a way to not enter the loop, just to skip an iteration.
If you are using ansible>=2.0, you can use a block
around your task with your condition:
- block:
- name: Do smthg with countvar
command: echo "{{ item }}"
with_sequence: start=1 end={{countvar.stdout|int}}
when: countvar.stdout|int > 0
But, as you said, it doesn't work (I didn't test my answer) because the end
value is evaluated anyway and the task fail. A solution is to protect it and then you can skip the block
part:
- name: Do smthg with countvar
command: echo "{{ item }}"
with_sequence: start=1 end={{countvar.stdout|int if countvar.stdout|int > 0 else 1}}
when: countvar.stdout|int > 0
Upvotes: 9