Jinja2中设置var的案例声明

Jinja2中设置var的案例声明

本文介绍了在Ansible/Jinja2中设置var的案例声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将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,则需要使用dict中不存在的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的案例声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 18:36