Jinja2 - variable inside a variable

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

I had to use this

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

Regards,
Vikas

this should also work:
{{ item.value[abcd]port }}

Thanks Brian, that is a neat option.

@vikas, can you please share the complete example, so that it will help others. Thanks

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