Ask Your Question
4

What is the method for terminating a loop based on a condition in Ansible?

asked 2021-09-29 11:00:00 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-07-19 09:00:00 +0000

david gravatar image

The method for terminating a loop based on a condition in Ansible is to use the "when" conditional statement along with the "break" keyword. For example, in a "loop" task, you can add a "when" statement that checks for a certain condition and then use "break" to terminate the loop when that condition is met.

Here is an example task:

- name: Terminate loop based on condition
  hosts: localhost
  vars:
    my_list:
      - item1
      - item2
      - item3
      - item4
  tasks:
    - name: Loop through list and terminate on condition
      debug:
        msg: "{{ item }}"
      loop: "{{ my_list }}"
      when: item == 'item3'
      break: yes

In this task, the "debug" task is looped through the "my_list" variable using the "loop" statement. The "when" statement checks if the current loop item is equal to "item3" and if true, the "break" statement is used to terminate the loop.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-09-29 11:00:00 +0000

Seen: 1 times

Last updated: Jul 19 '22