在Ansible中跳过整个循环

Nic*_*Roz 5 loops jinja2 conditional-statements ansible

如果我想在Ansible中跳过整个循环,我该怎么办?

根据指导方针,

whenwith_items(参见循环)结合使用时,... when语句将针对每个项目单独处理.

从而在运行这样的剧本时

---
- hosts: all
  vars:
    skip_the_loop: true
  tasks:
    - command: echo "{{ item }}"
      with_items: [1, 2, 3]
      when: not skip_the_loop
Run Code Online (Sandbox Code Playgroud)

我明白了

skipping: [localhost] => (item=1) 
skipping: [localhost] => (item=2) 
skipping: [localhost] => (item=3)
Run Code Online (Sandbox Code Playgroud)

而我不希望每次都检查一个条件.

然后我想出了使用内联条件的想法

- hosts: all
  vars:
    skip_the_loop: true
  tasks:
    - command: echo "{{ item }}"
      with_items: "{{ [1, 2, 3] if not skip_the_loop else [] }}"
Run Code Online (Sandbox Code Playgroud)

它似乎解决了我的问题,但后来我没有得到任何输出.我只想说一句话:

skipping: Loop has been skipped
Run Code Online (Sandbox Code Playgroud)

yda*_*coR 3

您应该能够使用 Ansible 2 的block使 Ansible 仅评估一次条件。

---
- hosts: all
  vars:
    skip_the_loop: true
  tasks:
    - block:
      - command: echo "{{ item }}"
        with_items: [1, 2, 3]
      when: not skip_the_loop
Run Code Online (Sandbox Code Playgroud)

对于每个项目和每个主机,这仍然会显示已跳过,但是,正如udondan指出的,如果您想抑制输出,您可以添加:

display_skipped_hosts=True
Run Code Online (Sandbox Code Playgroud)

到您的ansible.cfg 文件