Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break loop in Ansible? [duplicate]

Tags:

loops

ansible

Want to break the task after the value for item became 7, here is the sample task

   - hosts: localhost
     tasks:
       - shell: echo {{ item }}
         register: result
         with_sequence: start=4 end=16
         when: "{{ item }} < 7"

On the above code it's iterating the task from 4 to 16 as below

PLAY [localhost] ***********************************************************************************************************************************************

TASK [Gathering Facts] *****************************************************************************************************************************************
ok: [localhost]

TASK [command] *************************************************************************************************************************************************
 [WARNING]: when statements should not include jinja2 templating delimiters such as {{ }} or {% %}. Found: {{ item }} < 7

changed: [localhost] => (item=4)
changed: [localhost] => (item=5)
changed: [localhost] => (item=6)
skipping: [localhost] => (item=7)
skipping: [localhost] => (item=8)
skipping: [localhost] => (item=9)
skipping: [localhost] => (item=10)
skipping: [localhost] => (item=11)
skipping: [localhost] => (item=12)
skipping: [localhost] => (item=13)
skipping: [localhost] => (item=14)
skipping: [localhost] => (item=15)
skipping: [localhost] => (item=16)

PLAY RECAP *****************************************************************************************************************************************************
localhost                  : ok=2    changed=1    unreachable=0    failed=0
like image 389
V Mahaja Avatar asked Oct 28 '25 01:10

V Mahaja


1 Answers

Ansible runs the loop and

  • for items 4, 5, and 6 executes the echo command - shows changed status,

  • for remaining items it does not execute it - shows skipped status,

you have achieved what you wanted.


The only thing you can improve is getting rid of the warning by fixing the conditional:

- hosts: localhost
  tasks:
    - shell: echo {{ item }}
      register: result
      with_sequence: start=4 end=16
      when: "item|int < 7"
like image 133
techraf Avatar answered Oct 29 '25 16:10

techraf