Ansible:仅在未定义时设置变量 [英] Ansible: Set variable only if undefined

查看:28
本文介绍了Ansible:仅在未定义时设置变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 ansible 变量设置为某个默认值,但前提是该变量未定义.否则我想保持不变.

我尝试了这两种方法,它们都产生了递归循环:

namespace: "{{namespace|default(default_namespace)}}"命名空间:{% 如果定义了命名空间 %}{{namespace}}{% else %}{{default_namespace}}{% endif %}"

解决方案

您似乎采取了错误的方法.

查看有关 变量优先级.如果未定义变量,则使用默认变量是 Ansible 的内置功能.<​​/p>

在 Ansible 2.x 中,变量优先级如下所示:

<块引用>

角色默认

库存变量

所以如果你想为一个变量定义一个默认值,你应该在 role/defaults/main.yml 中设置它.仅当变量未在其他地方定义时,Ansible 才会使用该值.

另一种选择是使用 Jinja2 过滤器.使用 Jinja 过滤器,您可以为这样的变量设置默认值:

{{ some_variable |默认(5)}}

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.

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.

In Ansible 2.x the variable precedence starts like this:

role defaults

inventory vars

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.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆