简体   繁体   English

Ansible中的if语句与Jinja2变量

[英]if statement in Ansible with Jinja2 variables

I have a variable file in my ansible setup called vars.yml, this file contains many variables in this format: 我在ansible设置中有一个变量文件vars.yml,该文件包含许多这种格式的变量:

var1: 'val1'
var2: 'val2'

And it works fine, but I want to create new variables where the value is based on the value of another variable with an if statement - for example there could be: 它工作正常,但是我想创建一个新变量,其中该值基于带有if语句的另一个变量的值-例如,可能有:

"{% if var1|string() == 'val1' %} {% set var3 = 'val3' %} {% endif %}"

But this doesn't seem to work. 但这似乎不起作用。

Would that work for you? 那对你有用吗?

{% set var3 = {"val1": "val3"}[var1] | default("") %}

It defines a dict, of values, which makes it quite easy to extend unlike a dozen if/else's. 它定义了一个值的dict,与十二个if / else值不同,它很容易扩展。

{% set var3 = {"val1": "val3", "val2": "val4", "val5": "val6"}[var1] | default("") %}

You can make it even cleaner by defining it globally in your vars file 您可以通过在vars文件中全局定义它来使其更加整洁

var1: 'val1'
var2: 'val2'
traslationTable:
  val1: val3
  val2: val4
  val5: val6
var3: "{{ traslationTable[var1] | default('') }}"

Also see my answer in https://stackoverflow.com/a/30644252/2753241 另请参阅https://stackoverflow.com/a/30644252/2753241中的答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM