Filter 在ansible with_items循环中,根据条件跳过某些项
是否可以在不生成额外步骤的情况下,在条件下使用_items循环运算符跳过AnsibleFilter 在ansible with_items循环中,根据条件跳过某些项,filter,ansible,skip,Filter,Ansible,Skip,是否可以在不生成额外步骤的情况下,在条件下使用_items循环运算符跳过Ansible中的某些项 举个例子: - name: test task command: touch "{{ item.item }}" with_items: - { item: "1" } - { item: "2", when: "test_var is defined" } - { item: "3" } 在这个任务中,我只想在定义了test\u var的情况下
中的某些项
举个例子:
- name: test task
command: touch "{{ item.item }}"
with_items:
- { item: "1" }
- { item: "2", when: "test_var is defined" }
- { item: "3" }
在这个任务中,我只想在定义了test\u var
的情况下创建文件2。当对每个项目评估任务的条件时。因此,在这种情况下,您只需执行以下操作:
...
with_items:
- 1
- 2
- 3
when: item != 2 and test_var is defined
另一个答案很接近,但将跳过所有项目!=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
您想要的是始终创建文件1和文件3,但仅当定义了test\u var
时才创建文件2。如果您使用ansible的when条件,则它在完成任务时有效,而不是在如下单个项目上有效:
- name: test task
command: touch "{{ item.item }}"
with_items:
- { item: "1" }
- { item: "2" }
- { item: "3" }
when: test_var is defined
此任务将检查所有三个行项目1、2和3的条件
但是,您可以通过两个简单的任务来实现这一点:
- name: test task
command: touch "{{ item }}"
with_items:
- 1
- 3
- name: test task
command: touch "{{ item }}"
with_items:
- 2
when: test_var is defined
我也有类似的问题,我所做的是:
...
with_items:
- 1
- 2
- 3
when: (item != 2) or (item == 2 and test_var is defined)
更简单、更干净。我最近遇到了这个问题,我发现的答案都不是我想要的。我想要一种基于另一个变量选择性地包含with_项的方法。
以下是我的想法:
- name: Check if file exists
stat:
path: "/{{item}}"
with_items:
- "foo"
- "bar"
- "baz"
- "{% if some_variable == 'special' %}bazinga{% endif %}"
register: file_stat
- name: List files
shell: echo "{{item.item | basename}}"
with_items:
- "{{file_stat.results}}"
when:
- item.stat | default(false) and item.stat.exists
运行上述播放时,如果某个变量==“特殊”您关于“ansible's When condition work on complete task and not one items”的陈述是错误的,则文件统计中的项目列表将只包括bazinga。你看错我了,我自己说的和你说的一样。在我的回答中,我还提到“此任务将检查所有三行项目1、2和3的条件”。通过上面的语句,我的意思是这个when条件不仅适用于一个项目,而且适用于所有项目,这意味着整个任务。您可能需要when:(item==2,test_var已定义)或item!=2
;或者它永远不会为其他项目执行好的一点——这就是我在匆忙中解决这个问题所得到的结果您只需将和
切换到或
?