How can i get the value from a dict of dicts when the key is supplied by a variable ?

I have prepared a YAML file which arrange some constant values as dictionary of dictionaries:

values:
key1:
val1: 1.1
val2:
- 1.2.1
- 1.2.2
val3:
- 1.3.1
- 1.3.2
val4:
- 1.4.1
- 1.4.2
key2:
val1: 2.1
val2:
- 2.2.1
val3:
- 2.3.1
val4:
- 2.4.1

The values for first level of keys (key1,key2) will be provided to the playbook as variable ‘key’ and i am trying to use the dictionary values corresponding to the dictionary i get from this ‘key’. But i am unable to reference this dict within the playbook. I have tried some of these ways:

  • debug: msg=“value - {{values.{{key}}}.val1}”

  • debug: msg=“value - {{values[{{key}}]}}”

  • debug: msg=“value - {{values[{{key}}][val1]}}”

But nothing works. How can i refer to some keys in a dictionary via variables ?
And also, can someone guide me to a good resource which can educate me with the advanced syntax and usage of both YAML and Jinja2 ? I am sick of this hit and trial but couldn’t find a detailed resource either.

The values for first level of keys (key1,key2) will be provided to the
playbook as variable 'key' and i am trying to use the dictionary values
corresponding to the dictionary i get from this 'key'. But i am unable to
reference this dict within the playbook. I have tried some of these ways:

All of those include a common misunderstanding: The curly braces tell
Ansible "start (and stop) Jinja parsing", they don't delimit variables.
Once you're parsing Jinja, you don't need to start again in the middle.

I think you want something like

  - debug: msg="value - {{values[key]['val1']}}"

"values" and "key" aren't quoted, becuase they're variables. "val1" is,
because it's a literal string.

And also, can someone guide me to a good resource which can educate me
with the advanced syntax and usage of both YAML and Jinja2 ? I am sick
of this hit and trial but couldn't find a detailed resource either.

Others may have better ideas here, but I often use
http://docs.ansible.com/ansible/playbooks_filters.html and
http://jinja.pocoo.org/docs/dev/templates/ for Jinja help.

                                      -Josh (jbs@care.com)

(apologies for the automatic corporate disclaimer that follows)

This email is intended for the person(s) to whom it is addressed and may contain information that is PRIVILEGED or CONFIDENTIAL. Any unauthorized use, distribution, copying, or disclosure by any person other than the addressee(s) is strictly prohibited. If you have received this email in error, please notify the sender immediately by return email and delete the message and any attachments from your system.

Thanks. That worked perfectly fine.