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:
[WARNING]:当语句不应包含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屋!