ansible:检查变量列表的正确方法是否已设置? [英] ansible: correct way to check a list of variables has been set?
问题描述
我正在尝试在 Ansible 2.5 中使用 when: item is undefined
来检查是否已设置变量列表,如下所示:
I'm trying to use when: item is undefined
in Ansible 2.5 to check if a list of variables have been set, as below:
- hosts: all
tasks:
- name: validate some variables
fail:
msg: "Required variable {{item}} has not been provided"
when: item is undefined
loop:
- v1
- v2
然而,无论是否提供 v1
或 v2
,这都不会失败.
However, this never fails regardless of whether v1
or v2
are provided.
切换 when
以使用 jinja2 模板工作:
Switching the when
to use jinja2 templating works:
when: "{{item}} is undefined"
但是 ansible 抱怨这个:
But ansible complains about this:
[警告]:when 语句不应包含 jinja2 模板分隔符,例如 {{ }} 或 {% %}.发现:{{item}} 是未定义
[WARNING]: when statements should not include jinja2 templating delimiters such as {{ }} or {% %}. Found: {{item}} is undefined
循环遍历变量名称列表并检查它们是否已设置的正确方法是什么?
What is the correct way loop through a list of variable names and checked they have been set?
推荐答案
使用 vars
结构:
- name: validate some variables
fail:
msg: "Required variable {{item}} has not been provided"
when: vars[item] is undefined
loop:
- v1
- v2
或者,在 Ansible 2.5 中,使用新的 vars
查找插件:
Or, in Ansible 2.5, with the new vars
lookup plugin:
- name: validate some variables
debug:
when: lookup('vars', item) is undefined
loop:
- v1
- v2
虽然不是您指定的错误消息,而是查找插件的默认错误消息.
Although not with the error message you specified, but a default error message for a lookup plugin.
模块甚至不会被执行,所以你可以使用任何我在上面的例子中用 debug
替换 fail
的任何东西.
The module won't even be executed, so you can use whatever ー I replaced fail
with debug
in the example above.
这篇关于ansible:检查变量列表的正确方法是否已设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!