How to dynamically end a loop in Ansible

770 views
Skip to first unread message

ibelieve06

unread,
Jun 21, 2023, 6:56:44 PM6/21/23
to ansible...@googlegroups.com

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.

Vladimir Botka

unread,
Jun 21, 2023, 7:08:06 PM6/21/23
to ibelieve06, ansible...@googlegroups.com
On Wed, 21 Jun 2023 18:56:23 -0400
ibelieve06 <ibeli...@gmail.com> wrote:

> ... I need to dynamically end the loop earlier (lets say 5 iterations
> instead of 10 as defined by the loop: statements).

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

- command: "echo {{ item }}"
with_sequence: end=5
register: out
when: out.stdout|d(0)|int < 3

gives (on localhost)

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

--
Vladimir Botka

Vladimir Botka

unread,
Jun 21, 2023, 7:20:00 PM6/21/23
to ibelieve06, ansible...@googlegroups.com
See "Ansible loop interface redesign #140"
https://github.com/ansible/proposals/issues/140

--
Vladimir Botka
Reply all
Reply to author
Forward
0 new messages