在 Ansible/Jinja2 中设置 var 的 case 语句 [英] Case statement for setting var in Ansible/Jinja2
问题描述
我将 Ansible 与 Jinja2 模板一起使用,这是我无法在 Ansible 的文档中找到解决方案或在谷歌上搜索 Jinja2 示例的情况.这是我想在 Ansible 中实现的逻辑:
I'm using Ansible with Jinja2 templates, and this is a scenario that I can't find a solution for in Ansible's documentation or googling around for Jinja2 examples. Here's the logic that I want to achieve in Ansible:
if {{ existing_ansible_var }} == "string1"
new_ansible_var = "a"
else if {{ existing_ansible_var }} == "string2"
new_ansible_var = "b"
<...>
else
new_ansible_var = ""
我可能可以通过结合几种技术来做到这一点,这里的变量赋值:在 jinja 中设置变量,这里的条件比较:http://jinja.pocoo.org/docs/dev/templates/#if-expression,以及这里的默认过滤器:https://docs.ansible.com/playbooks_filters.html#defaulting-undefined-variables ,
I could probably do this by combining several techniques, the variable assignment from here: Set variable in jinja, the conditional comparison here: http://jinja.pocoo.org/docs/dev/templates/#if-expression, and the defaulting filter here: https://docs.ansible.com/playbooks_filters.html#defaulting-undefined-variables ,
...但我觉得这太过分了.有没有更简单的方法来做到这一点?
...but I feel like that's overkill. Is there a simpler way to do this?
推荐答案
如果您只想根据 existing_ansible_var
的值在模板中输出一个值,您只需使用 dict 并提供它使用 existing_ansible_var
.
If you just want to output a value in your template depending on the value of existing_ansible_var
you simply could use a dict and feed it with existing_ansible_var
.
{{ {"string1": "a", "string2": "b"}[existing_ansible_var] | default("") }}
你可以用同样的方式定义一个新变量:
You can define a new variable the same way:
{% set new_ansible_var = {"string1": "a", "string2": "b"}[existing_ansible_var] | default("") -%}
<小时>
如果 existing_ansible_var
可能不一定被定义,你需要用一个 default()
来捕捉它,它在你的字典中不存在:
In case existing_ansible_var
might not necessarily be defined, you need to catch this with a default()
which does not exist in your dict:
{"string1": "a", "string2": "b"}[existing_ansible_var | default("this key does not exist in the dict")] | default("")
<小时>
您也可以在剧本中定义它,然后在模板中使用 new_ansible_var
:
vars:
myDict:
string1: a
string2: b
new_ansible_var: '{{myDict[existing_ansible_var | default("this key does not exist in the dict")] | default("") }}'
这篇关于在 Ansible/Jinja2 中设置 var 的 case 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!