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
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
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