Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible - condition on with_sequence loop with variable end that could be less than start

Tags:

loops

ansible

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
like image 735
JohnLoopM Avatar asked Oct 14 '25 18:10

JohnLoopM


1 Answers

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
like image 123
zigarn Avatar answered Oct 18 '25 04:10

zigarn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!