在ansible with_items循环中跳过某些条件

m_m*_*iah 11 skip filter ansible

是否有可能在有条件的情况下跳过Ansible with_items循环运算符中的某些项,而不会产生额外的步骤?

仅举例如:

- name: test task
    command: touch "{{ item.item }}"
    with_items:
      - { item: "1" }
      - { item: "2", when: "test_var is defined" }
      - { item: "3" }
Run Code Online (Sandbox Code Playgroud)

在此任务中,我只想在test_var定义时创建文件2 .

Pet*_*026 17

另一个答案是关闭,但将跳过所有项目!= 2.我不认为这是你想要的.这是我要做的:

- hosts: localhost
  tasks:
  - debug: msg="touch {{item.id}}"
    with_items:
    - { id: 1 }
    - { id: 2 , create: "{{ test_var is defined }}" }
    - { id: 3 }
    when: item.create | default(True) | bool
Run Code Online (Sandbox Code Playgroud)


nit*_*one 5

when:将为每个项目评估任务的条件。因此,在这种情况下,您可以执行以下操作:

...
with_items:
- 1
- 2
- 3
when: item != 2 and test_var is defined
Run Code Online (Sandbox Code Playgroud)

  • 您可能希望使用“何时:(项目== 2并且定义了test_var)或项目!= 2”;否则它将永远不会为其他项目执行 (2认同)

lon*_*nix 5

我遇到了类似的问题,我所做的是:

...
with_items:
  - 1
  - 2
  - 3
when: (item != 2) or (item == 2 and test_var is defined)
Run Code Online (Sandbox Code Playgroud)

哪个更简单,更干净。