6

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 {{ item.value.abcd.port }} works fine, but key 'abcd' varies in each dictionary.

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 %}

Or without using a variable at all, something like this

{{ item.value.[item.value.keys().1].port }}

1 Answer 1

10

I had to use either of these to use a variable inside a variable.

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

I didn't wanted to hardcode my Jinja2 templates, this is exactly what I was looking for.

Sign up to request clarification or add additional context in comments.

2 Comments

Could you show me how the variable nginx_dir looks like, how to set the value on it when it is dynamically changed.
The directory is /opt/nginx/conf.d/something. I had used a dictionary, and then looped over it. Sorry, it has been a while, I don’t have the exact code to show you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.