在Jinja2模板中循环Ansible变量数组


12

当Ansible收集有关主机的事实时,例如获取主机的所有坐骑:

 "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"
            }, 

等等。因此,我想做的是:在模板中,我想遍历数组中的所有对象,并输出每个“ mount”键的值。

我这样尝试:

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

但这是行不通的。我尝试了其他类似iteritems()的东西,但无法正常工作。据我所知,Ansible的输出在json中,如果有帮助的话。有人知道解决方案,还是更多关于stackoverflow的问题?

感谢您的回答。

Answers:


17

您有一个简单的语法错误;您应该使用花括号而不是括号。

您目前有:

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

这些应该是大括号,而不是括号,即{%%}

此外,您在for中选择的变量名是mounts,因此这是您在循环内部实际使用以获得每个对象的名称。

最后,不需要在for循环中用大括号括住变量。

更正这些错误会导致此问题,它应该可以正常工作:

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

该死的用大括号读了评论...如果您不小心先复制了错误的方块,很难发现。:(
马库斯
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.