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