Loop over Ansible variable array in Jinja2 template

ThatGuyOnTheNet asked:

when Ansible gathers facts about hosts, it for example gets all the mounts of the host:

 "ansible_mounts": [
            {
                "block_available": 7800291, 
                "block_size": 4096, 
                "block_total": 8225358, 
                "block_used": 425067, 
                "device": "/dev/mapper/foobar", 
                "fstype": "xfs", 
                "inode_available": 16403366, 
                "inode_total": 16458752, 
                "inode_used": 55386, 
                "mount": "/", 
                "options": "rw,seclabel,relatime,attr2,inode64,noquota", 
                "size_available": 31949991936, 
                "size_total": 33691066368, 
                "uuid": "2ebc82cb-5bc2-4db9-9914-33d65ba350b8"
            }, 
            {
                "block_available": 44648, 
                "block_size": 4096, 
                "block_total": 127145, 
                "block_used": 82497, 
                "device": "/dev/sda1", 
                "fstype": "xfs", 
                "inode_available": 255595, 
                "inode_total": 256000, 
                "inode_used": 405, 
                "mount": "/boot", 
                "options": "rw,seclabel,relatime,attr2,inode64,noquota", 
                "size_available": 182878208, 
                "size_total": 520785920, 
                "uuid": "c5f7eaf2-5b70-4f74-8189-a63bb4bee5f8"
            }, 

And so on.
So what I want to do is:
In a template I want to loop over all the objects in the array and output the values of each “mount” key.

I try it like this:

    (% for mounts in {{ ansible_mounts }} %)
    Mountpoint: {{ ansible_mounts.mount }}
    (% endfor %)

But it does not work.
I tried around with some other stuff like iteritems() but I cannot get it to work. As far as I know the output of Ansible is in json, if that helps anybody.
Does somebody know the solution or is this more of a question for stackoverflow?

Thanks for any answers.

My answer:


You have a simple syntax error; you should be using brace brackets instead of parentheses.

You currently have:

(% for mounts in {{ ansible_mounts }} %)
Mountpoint: {{ ansible_mounts.mount }}
(% endfor %)

These should be braces, not parentheses, that is, {% and %}.

Further, the variable name you selected in for is mounts, so that is what you should be actually using inside the loop to get each object.

Finally, the braces around the variable in the for loop aren’t necessary.

Correcting these errors results in this, which should work fine:

{% for mounts in ansible_mounts %}
Mountpoint: {{ mounts.mount }}
{% endfor %}

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.