jinja2 - loop through a dictionary
Solution 1
The below would create a output with all the user names in it
{% for item in test123.values() %}
name of the user: {{ item.name }}
{% endfor %}
Output format:
name of the user: test1
name of the user: test2
If you need something in specific format let me know the desired output
Solution 2
An option would be to use dict2items filter. The template below
{% for item in test123|dict2items %}
{{ item }}
{% endfor %}
{% for item in test123|dict2items %}
key: {{ item.key }}
value.number: {{ item.value.number }}
value.name: {{ item.value.name }}
value.path: {{ item.value.path }}
{% endfor %}
gives
{'value': {u'path': u'/tmp/test.txt', u'name': u'test1', u'number': 1}, 'key': u'testA'}
{'value': {u'path': u'/tmp/test.txt', u'name': u'test2', u'number': 2}, 'key': u'testB'}
key: testA
value.number: 1
value.name: test1
value.path: /tmp/test.txt
key: testB
value.number: 2
value.name: test2
value.path: /tmp/test.txt
Related videos on Youtube
Mladen Nikolic
Updated on June 04, 2022Comments
-
Mladen Nikolic almost 2 years
I am new with
Jinja2
maybe my question is noobie but I can't understand it.So I use
Jinja2
for anAnsible
task as a template to create a file, I have a dictionary defined in the Default Variable file like:test123: testA: name: test1 number: 1 path: /tmp/test.txt testB: name: test2 number: 2 path: /tmp/test.txt
Now in my
Jinja2
file, I want to loop through this dictionary and print everything defined in the dictionary.I tried various examples but nothing does the right thing.
For example:
{% for item in test123.values() -%} {{ item.name }}="{{ item.number }}" {%- endfor %} {% for item in test123.testB.values() -%} {{ item.name }}="{{ item.number }}" {%- endfor %}
Error Message:
fatal: [testserver]: FAILED! => {"changed": false, "msg": "AnsibleUndefinedVariable: 'ansible.parsing.yaml.objects.AnsibleUnicode object' has no attribute 'name'"}
I thought maybe the best thing would be to create a while loop for this and print everything out but since in
Jinja2
there is no while loop I am a little bit confused how to do it.Do someone has an idea how to achieve that? So once again the goal is to print everything from the dictionary in the
Jinja2
file.Thank you in advance
-
amanb about 5 yearsThat is not a Python dictionary..not sure about Ansible.
-
ozlevka about 5 yearsWhat python version on target host?
-
Mladen Nikolic about 5 years@amanb I used this manual for creating a dictionary in ansible: docs.ansible.com/ansible/latest/plugins/lookup/dict.html ( in the example at the top you can see the example) so jinja2 can't do anything with that dictionary?
-
Mladen Nikolic about 5 years@ozlevka python version on the target host is: Python 2.7.5
-
-
Mladen Nikolic about 5 yearsWorks as expected :) so the .values() calls all the values in the dict right?
-
error404 about 5 yearsyes. then you can access the subelements using the item.name and {{ }} is used for variable replacement in jinja2