How can I break the with_items loop based on a condition

和自甴很熟 提交于 2019-12-23 20:27:33

问题


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.

回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/53171738/how-can-i-break-the-with-items-loop-based-on-a-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!