Ansible:应用何时完成循环 [英] Ansible: apply when to complete loop
问题描述
我想将 ansible 中的循环与应用于它的 when 语句结合起来.然而,当语句应用于每个循环迭代时,这消除了将一个应用于完整循环的可能性.有人知道怎么做吗?
I want to combine a loop in ansible with a when-statement applied to it. When-statements are applied to each loop iteration however, which takes away the possibility to apply one to the complete loop. Does anyone know how to do this?
我以前遇到过这个问题,但在这种特定情况下,它涉及一个可能存在也可能不存在的变量.我想做的是:
I've run into this problem before, but in this specific case it concerns a variable that might or might not exist. What I would want to do is something like:
- name: Loop
debug:
msg: "{{ item }}"
with_items: x.y|default([])
but-only-run-this-loop-when: x is defined
默认过滤器处理那些未定义 y 的情况.由于在我的情况下 x 可能还没有定义,我需要但仅运行此循环时.显然,这不是一个真正的 ansible 声明.我应该用什么代替?
The default-filter takes care of those instances where y is not defined. Since in my case x might als be not defined, I need the but-only-run-this-loop-when. Obviously, this is not a real ansible statement. What should I use in stead?
目前,我使用一些可怕的东西:
Currently, I use something horrible like:
- name: kludge1
set_fact:
fake_y : "{{ [] }}"
- name: kludge2
set_fact:
fake_y : "{{ x.y|default([]) }}"
when: x is defined
- name: Loop
debug:
msg: "{{ item }}"
with_items: '{{ fake_y }}'
例如在 host_vars 中:
With for example in host_vars:
x:
y:
- "foo"
- "bar"
但我敢肯定那不是要走的路.
But I'm sure that's not the way to go.
推荐答案
有类似的答案 此处.您可以连续使用多个默认值:
There's similar answer here. You can use several defaults in a row:
- name: Loop
debug:
msg: "{{ item }}"
with_items: (x | default({})).y | default([])
并且没有办法将 when
语句绑定到整个循环任务(至少在当前的 Ansible 2.2 中).
And there is no way to bound when
statement to looped task as a whole (at least in current Ansible 2.2).
这篇关于Ansible:应用何时完成循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!