# using a variable as a key to a dictionary

**URL:** <https://forum.ansible.com/t/using-a-variable-as-a-key-to-a-dictionary/15819>\
**Category:** Ansible Project\
**Created:** [July 31, 2014, 8:41am UTC](https://forum.ansible.com/t/using-a-variable-as-a-key-to-a-dictionary/15819 "2014-07-31T08:41:16Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Yves\_Dorfsman](https://avatars.discourse-cdn.com/v4/letter/y/9de0a6/32.png) [@Yves\_Dorfsman](https://forum.ansible.com/u/Yves_Dorfsman)\
**Post date:** [July 31, 2014, 8:41am UTC](https://forum.ansible.com/t/using-a-variable-as-a-key-to-a-dictionary/15819/1 "2014-07-31T08:41:16Z")

</div>

With jinja2, is it possible to use a variable as a key to a dictionary?  
The following doesn't work:

var file:  
db\_names:  
&nbsp;&nbsp;- prod  
&nbsp;&nbsp;- dev  
&nbsp;&nbsp;- qa

databases:  
&nbsp;&nbsp;prod:  
&nbsp;&nbsp;&nbsp;&nbsp;connection\_string: prod\_conn\_string  
&nbsp;&nbsp;qa:  
&nbsp;&nbsp;&nbsp;&nbsp;connection\_string: qa\_conn\_string  
&nbsp;&nbsp;dev:  
&nbsp;&nbsp;&nbsp;&nbsp;connection\_string: dev\_conn\_string

playbook:  
- name: test  
&nbsp;&nbsp;debug: msg="database conn string: {{ databases.{{item}}.connection\_string }}  
&nbsp;&nbsp;with\_items: db\_names

---

<div class="post-metadata">

**Author:** ![Yves\_Dorfsman](https://avatars.discourse-cdn.com/v4/letter/y/9de0a6/32.png) [@Yves\_Dorfsman](https://forum.ansible.com/u/Yves_Dorfsman)\
**Post date:** [July 31, 2014, 9:23am UTC](https://forum.ansible.com/t/using-a-variable-as-a-key-to-a-dictionary/15819/2 "2014-07-31T09:23:32Z")

</div>

Got it (from [http://jinja.pocoo.org/docs/templates](http://jinja.pocoo.org/docs/templates), right in "Variables"):  
- name: test  
&nbsp;&nbsp;debug: msg="database conn string: {{ databases[item].connection\_string }}  
&nbsp;&nbsp;with\_items: db\_names
