如何根据条件打破 with_items 循环

问题描述 投票:0回答:2

我想根据条件打破 with_items 循环。为了论证,该条件是命令的标准输出是否等于特定字符串。

显然下面的例子不起作用,但这是我想要做的一个想法。

例如:

- 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.
ansible jinja2 ansible-2.x ansible-inventory ansible-template
2个回答
0
投票

如果您想中止整个剧本,请尝试以下操作:

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

或者您可以添加

ignore_errors: yes


0
投票

可以在

when
条件下打破循环。为了使其与
shell
输出一起使用,必须预定义注册变量
shell_command
,以便它在第一个循环评估中存在。

---
- name: "loop-break.yaml"
  hosts: localhost

  vars:
    shell_command:
      stdout: ""

  tasks:
    - name: testing loop
      shell: "echo {{ item }}"
      loop:
        - "one"
        - "two"
        - "three"
      register: shell_command
      when: not condition
      vars:
        condition: "{{ 'two' in shell_command.stdout }}"

    - name: "debug results"
      debug:
        msg: "{{ item.item }}"
      loop: "{{ shell_command.results }}"

虽然有点hacky,但是很有效。

© www.soinside.com 2019 - 2024. All rights reserved.