在 Ansible 中有条件地定义变量 [英] Conditionally define variable in Ansible
问题描述
我想在 Ansible 剧本中有条件地定义一个变量,如下所示:
I want to conditionally define a variable in an Ansible playbook like this:
my_var: "{{ 'foo' if my_condition}}"
如果条件未解析为 true
,我希望变量保持未定义状态.
I would like the variable to remain undefined if the condition does not resolve to true
.
如果我尝试执行代码,Ansible 会出现以下错误:
Ansible gives the following error if I try to execute the code:
fatal: [foo.local] => {'msg': 'AnsibleUndefinedVariable: One or more undefined
variables: the inline if-expression on line 1 evaluated
to false and no else section was defined.', 'failed': True}
为什么这是一个错误?
完整的案例如下所示:
{role: foo, my_var: "foo"}
如果定义了 my_var
,角色会做一些特别的事情.在某些情况下,我不希望角色这样做.我可以使用 when:condition
,但是我必须复制整个角色块.我也可以使用额外的 bool 变量,但我想要一个无需将接口"更改为角色的解决方案.
If my_var
is defined, the role does something special. In some cases, I don't want the role to do this. I could use when: condition
, but then I would have to copy the whole role block. I could also use an extra bool variable, but I would like a solution without having to change the "interface" to the role.
有什么想法吗?
推荐答案
你可以这样使用:
my_var: "{{ 'foo' if my_condition else '' }}"
如果条件不匹配,'else' 将发生,在这种情况下,将为变量设置一个空值.我认为这是一个简短、可读且优雅的解决方案.
The 'else' will happen if condition not match, and in this case will set a empty value for the variable. I think this is a short, readable and elegant solution.
这篇关于在 Ansible 中有条件地定义变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!