pythonansiblejinja2

jinja2 - loop through a dictionary


I am new with Jinja2 maybe my question is noobie but I can't understand it.

So I use Jinja2 for an Ansible 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


Solution

  • 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