Neil
Neil

Reputation: 25905

How to use nested variables (dictionary keys) in Ansible?

Feel free to suggest or directly edit my question if it's not expressed clearly.

I have some nested variables declared in Ansible like this:

# vars/main.yml
parent_key:
  child_key1: "child_value1"
  child_key2: "Resolving: {{ child_key1 }}"

But Ansible says: child_key1 not defined or something similar.

However, this also doesn't work:

# vars/main.yml
parent_key:
  child_key1: "child_value1"
  child_key2: "Resolving: {{ parent_key.child_key1 }}"

Ansible says something like Could not template ....

The results are almost the same for Ansible 1.9.4 and Ansible 2.0.0.2.

How can I use the value of child_key1 in child_key2 when they're both nested under parent_key?

Note that the same concept without nesting the keys works fine:

# vars/main.yml (without nesting at all)
child_key1: "child_value1"
child_key2: "Resolving: {{ child_key1 }}"

Upvotes: 2

Views: 2976

Answers (1)

udondan
udondan

Reputation: 60059

You can't. This indeed was working in earlier Ansible versions but Ansible now prevents this.

The problem is you're trying to reference an object which somehow is in the process of being defined.

In this bug report on Github some users were discussing this topic.


As for a solution... how about a combination of both. Something like this:

key1: &key1 "child_value1"

parent_key:
  child_key1: *key1
  child_key2: "Resolving: {{ key1 }}"

Yes that's ugly, but at least prevents you from repeating the values.

Upvotes: 4

Related Questions