Ansible:仅在未定义的情况下设置变量 [英] Ansible: Set variable only if undefined
问题描述
我想将ansible变量设置为某个默认值,但前提是该变量未定义.否则,我想保持不变.
I would like to set an ansible variable to some default value but only if the variable is undefined. Otherwise I would like to keep it unchanged.
我尝试了这两种方法,它们都产生了递归循环:
I tried these two approaches and both of them produce recursive loop:
namespace: "{{namespace|default(default_namespace)}}"
namespace: "{% if namespace is defined %}{{namespace}}{% else %}{{default_namespace}}{% endif %}"
推荐答案
您似乎采取了错误的方法.
It seems like you are taking a wrong approach.
看看有关可变优先级.如果未定义变量,则Ansible的内置功能是使用默认变量.
Take a look at the Ansible documentation concerning variable precedence. It is a built-in feature of Ansible to use the default variable if the variable is not defined.
在Ansible 2.x中,变量优先级如下所示:
In Ansible 2.x the variable precedence starts like this:
角色默认值
库存变量
因此,如果要为变量定义默认值,则应在role/defaults/main.yml
中进行设置.仅当未在其他位置定义变量时,Ansible才会使用该值.
So if you want to define a default value for a variable you should set it in role/defaults/main.yml
. Ansible will use that value only if the variable is not defined somewhere else.
另一种选择是使用 Jinja2过滤器.使用Jinja过滤器,您可以为这样的变量设置默认值:
Another option is to use a Jinja2 filter. With a Jinja filter you can set a default value for a variable like this:
{{ some_variable | default(5) }}
这篇关于Ansible:仅在未定义的情况下设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!