Whenever I try to make Ansible interpret a nested variable — so, a variable inside another variable — I cannot get the result I expect.
Given the variables:
key: bar
foo:
bar: baz
foo_bar: baz
I have tried those three approaches without much luck to dynamically access the key bar of the dictionary foo or the key foo_bar, when constructed from the value of key:
-
- ansible.builtin.debug: msg: "{{ foo[{{ key }}] }}"But, I get the error:
'template error while templating string: expected token '':'', got ''}''. String: {{ foo[{{ key }}] }}'
-
- ansible.builtin.debug: msg: "{{ foo_{{ key }} }}"But, I get a similar error
'template error while templating string: expected token ''end of print statement'', got ''{''. String: {{ foo_{{ key }} }}'
-
- ansible.builtin.debug: msg: "{{ foo['{{ key }}'] }}"And here, I get the error
The task includes an option with an undefined variable. The error was: 'dict object' has no attribute '{{ key }}'
I was expecting to get the value of foo.bar or foo_bar, so baz.
What would be the correct approach to achieve this?