# How to dynamically end a loop in Ansible

**URL:** <https://forum.ansible.com/t/how-to-dynamically-end-a-loop-in-ansible/38140>\
**Category:** Ansible Project\
**Created:** [June 21, 2023, 10:56pm UTC](https://forum.ansible.com/t/how-to-dynamically-end-a-loop-in-ansible/38140 "2023-06-21T22:56:23Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![ibelieve06](https://avatars.discourse-cdn.com/v4/letter/i/7feea3/32.png) [@ibelieve06](https://forum.ansible.com/u/ibelieve06)\
**Post date:** [June 21, 2023, 10:56pm UTC](https://forum.ansible.com/t/how-to-dynamically-end-a-loop-in-ansible/38140/1 "2023-06-21T22:56:23Z")

</div>

Due to the fact that we cannot run loop on block with Ansible, therefore I have to do `include_tasks` in the loop where the referenced file contains more than 1 task.

What if I need to dynamically end the loop earlier (lets say 5 iterations instead of 10 as defined by the `loop:` statements). trying to use `when:` condition but that only take in pre-defined/statically defined variables, if I have to update the variable that will be evaluated in `when:` for each iteration, I have to do `register:` or `set_fact` in a task before that, which is not possible when the loop task is running…

Also in the `included_tasks` I can set `meta: end_play` to end the loop and the play execution but that is not what I want, the play should continue after the loop.

---

<div class="post-metadata">

**Author:** ![vbotka](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/vbotka/32/359_2.png) [@vbotka](https://forum.ansible.com/u/vbotka)\
**Post date:** [June 21, 2023, 11:07pm UTC](https://forum.ansible.com/t/how-to-dynamically-end-a-loop-in-ansible/38140/2 "2023-06-21T23:07:45Z")

</div>

You can't end it. You can only skip the rest. For example,

&nbsp;&nbsp;&nbsp;&nbsp;- command: "echo {{ item }}"  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;with\_sequence: end=5  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;register: out  
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;when: out.stdout|d(0)|int \< 3

gives (on localhost)

&nbsp;&nbsp;changed: [localhost] =\> (item=1)  
&nbsp;&nbsp;changed: [localhost] =\> (item=2)  
&nbsp;&nbsp;changed: [localhost] =\> (item=3)  
&nbsp;&nbsp;skipping: [localhost] =\> (item=4)  
&nbsp;&nbsp;skipping: [localhost] =\> (item=5)

---

<div class="post-metadata">

**Author:** ![vbotka](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/vbotka/32/359_2.png) [@vbotka](https://forum.ansible.com/u/vbotka)\
**Post date:** [June 21, 2023, 11:19pm UTC](https://forum.ansible.com/t/how-to-dynamically-end-a-loop-in-ansible/38140/3 "2023-06-21T23:19:39Z")

</div>

See "Ansible loop interface redesign #140"  
[https://github.com/ansible/proposals/issues/140](https://github.com/ansible/proposals/issues/140)
