How can I break the with_items loop based on a condition

Viewed 2841

I want to break out of the with_items loop based on a condition. That condition for arguments sake is if the stdout of a command is equal to a particular string.

Obviously the example below does not work but this is an idea of what I want to do.

For example:

- name: testing loop
  shell: "echo {{ item }}"
  with_items:
     - "one"
     - "two"
     - "three"
  register: shell_command # registering the shell command and it's attributes
  when: shell_command.stdout == "two" # break once the stdout of the run shell command matches the string "two". So it will run twice and break on the second.
2 Answers

This seems not possible at the moment as you can see here. There exists an untested hack out there.

If you want to abort whole playbook, try this:

 - name: testing loop
            shell: "echo {{ item }}"
            with_items:
              - "one"
              - "two"
              - "three"
            register: shell_command
            failed_when: "'two' in shell_command.stdout"

Or you can just add ignore_errors: yes

Related