Jinja2 - variable inside a variable

3,200 views
Skip to first unread message

Vikas Kumar

unread,
Oct 6, 2015, 10:40:34 PM10/6/15
to Ansible Project
Hello Everyone,

I am trying to iterate over a dictionary in a Jinja2 template (in Ansible). One of the arrays or keys in the dictionary is 'abcd'
This works fine, but key 'abcd' varies in each dictionary.
{{ item.value.abcd.port }}


I am looking to do something like below using a variable 'nginx_dir'.
{% set nginx_dir = item.value.keys().1 %}
{% set my_port = item.value.nginx_dir.port %}

Regards,
Vikas

Vikas Kumar

unread,
Oct 7, 2015, 1:14:09 AM10/7/15
to Ansible Project
I had to use this 

{% set my_port = item.value.get(nginx_dir).port %}

Regards,
Vikas

Brian Coca

unread,
Oct 7, 2015, 2:57:06 PM10/7/15
to Ansible Project
this should also work:
{{ item.value[abcd]port }}


--
Brian Coca

Vikas Kumar

unread,
Oct 7, 2015, 8:58:55 PM10/7/15
to Ansible Project
Thanks Brian, that is a neat option.

Arbab Nazar

unread,
Oct 8, 2015, 12:10:43 PM10/8/15
to Ansible Project
@vikas, can you please share the complete example, so that it will help others. Thanks

Vikas Kumar

unread,
Oct 8, 2015, 12:27:55 PM10/8/15
to Ansible Project
Hi Arbab,

Here you go.

I have multiple fact files generated thru YAML files. Consider below yaml file as an example, which I have converted into JSON and placed in ansible facts directory. See this thread for converting YAML into JSON and store them as facts.

---
app_name
: dev1
apps
.d:
  port
: 1234
  server
: test1
  instance
: dev


When iterating over ansible facts, I didn't wanted to hard code anything in playbooks or Jinja2 templates, thus below variables becomes very handy.

{% set nginx_dir = item.value.keys().1 %}
{% set my_port = item.value[nginx_dir].port %}
{% set my_instance = item.value[nginx_dir].instance %}

Here, the first line will have apps.d variable in nginx_dir
and second line will have 1234 in my_port variable and so on.

Now, you can these use variables in the Jinja2 template.

Hope this helps.

Regards,
Vikas
Reply all
Reply to author
Forward
0 new messages