跳过 Ansible 中的整个循环
Skip the whole loop in Ansible
在Ansible中想跳过整个循环怎么办?
根据指南,
While combining when
with with_items
(see Loops), ... when
statement is processed separately for each item.
因此 运行 那样的剧本
---
- hosts: all
vars:
skip_the_loop: true
tasks:
- command: echo "{{ item }}"
with_items: [1, 2, 3]
when: not skip_the_loop
我明白了
skipping: [localhost] => (item=1)
skipping: [localhost] => (item=2)
skipping: [localhost] => (item=3)
而我不希望每次都检查条件。
然后我想到了使用内联条件
- hosts: all
vars:
skip_the_loop: true
tasks:
- command: echo "{{ item }}"
with_items: "{{ [1, 2, 3] if not skip_the_loop else [] }}"
它似乎解决了我的问题,但后来我没有得到任何输出。我只想要一行:
skipping: Loop has been skipped
您应该能够使用 Ansible 2 的 blocks.
让 Ansible 仅评估一次条件
---
- hosts: all
vars:
skip_the_loop: true
tasks:
- block:
- command: echo "{{ item }}"
with_items: [1, 2, 3]
when: not skip_the_loop
对于每个项目和每个主机,这仍然会显示已跳过,但是,正如 udondan 指出的那样,如果您想抑制输出,您可以添加:
display_skipped_hosts=True
给你的 ansible.cfg file.
这可以使用 include
和条件轻松完成:
hosts: all
vars:
skip_the_loop: true
tasks:
- include: loop
when: not skip_the_loop
而在 tasks/
的某处有一个名为 loop.yml
的文件:
- command: echo "{{ item }}"
with_items: [1, 2, 3]
在Ansible中想跳过整个循环怎么办?
根据指南,
While combining
when
withwith_items
(see Loops), ...when
statement is processed separately for each item.
因此 运行 那样的剧本
---
- hosts: all
vars:
skip_the_loop: true
tasks:
- command: echo "{{ item }}"
with_items: [1, 2, 3]
when: not skip_the_loop
我明白了
skipping: [localhost] => (item=1)
skipping: [localhost] => (item=2)
skipping: [localhost] => (item=3)
而我不希望每次都检查条件。
然后我想到了使用内联条件
- hosts: all
vars:
skip_the_loop: true
tasks:
- command: echo "{{ item }}"
with_items: "{{ [1, 2, 3] if not skip_the_loop else [] }}"
它似乎解决了我的问题,但后来我没有得到任何输出。我只想要一行:
skipping: Loop has been skipped
您应该能够使用 Ansible 2 的 blocks.
让 Ansible 仅评估一次条件---
- hosts: all
vars:
skip_the_loop: true
tasks:
- block:
- command: echo "{{ item }}"
with_items: [1, 2, 3]
when: not skip_the_loop
对于每个项目和每个主机,这仍然会显示已跳过,但是,正如 udondan 指出的那样,如果您想抑制输出,您可以添加:
display_skipped_hosts=True
给你的 ansible.cfg file.
这可以使用 include
和条件轻松完成:
hosts: all
vars:
skip_the_loop: true
tasks:
- include: loop
when: not skip_the_loop
而在 tasks/
的某处有一个名为 loop.yml
的文件:
- command: echo "{{ item }}"
with_items: [1, 2, 3]