有条件地在Ansible中定义变量

编程入门 行业动态 更新时间:2024-10-28 14:24:36
本文介绍了有条件地在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中定义变量

本文发布于:2023-07-26 11:37:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1215988.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有条件   变量   定义   Ansible

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!