1

I have a variable file in my ansible setup called vars.yml, this file contains many variables in this format:

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 var1|string() == 'val1' %} {% set var3 = 'val3' %} {% endif %}"

But this doesn't seem to work.

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
user3473280
  • 67
  • 1
  • 6

1 Answers1

2

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.

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

You can make it even cleaner by defining it globally in your vars file

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

Community
  • 1
  • 1
udondan
  • 57,263
  • 20
  • 190
  • 175
  • I tried this in my vars file: var1: 'val1' var3: "{% set var3 = {'val1': 'val3'}[var1] | default('') %}" but when templating the replaced value is just "" – user3473280 Nov 17 '15 at 11:45
  • Don't use `set` in your vars file, just assign the value like this: `var3: "{{ {'val1': 'val3'}[var1] | default('') }}"` – udondan Nov 17 '15 at 11:49