codiac
codiac

Reputation: 1991

ansible cannot use variable

I created a role and with a variables file named defaults/main.yml with following content:

level1:
  level2_1:
    level3_1: "value_3_1"
  level2_2:
    level3_2: "value_3_2"
    level3_3: "{{ level1.level2_1.level3_1 }} {{  level1.level2_2.level3_2  }}"

When I try running inside a task file it throws An unhandled exception occurred while templating.

I have tried changing the level3_3 line without adding parrents but also throws an error.

The only way I found to work is if I remove indentation from level3_3 which will not make it part of the structure.

How can I compose a variable similar to level3_3 inside the structure without throwing an error?

Upvotes: 1

Views: 187

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68189

It's not possible by design. See Can't reference a dict key inside the same dict #50280. Either create compounds outside the dictionary or put the repeating values into a variables. For example

val_A: value_3_1
val_B: value_3_2

level1:
  level2_1:
    level3_1: "{{ val_A }}"
  level2_2:
    level3_2: "{{ val_B }}"
    level3_3: "{{ val_A }} {{ val_B }}"

I'd prefer this structure. It's simpler and less error-prone.

Upvotes: 3

Related Questions