Home > Software engineering >  taking mount name and size from ansible facts using jinja 2 for loop
taking mount name and size from ansible facts using jinja 2 for loop

Time:09-17

I am losing my hope to solve this simple task...

All I need is take parameters "size_total" and "mount" from this loop:

{% for host in groups['test'] %}
        {{ hostvars[host]['ansible_facts']['mounts'] }}
{% endfor %}


above gives me this:

        [{'mount': '/', 'device': '/dev/mapper/rhel_rhel84-root', 'fstype': 'xfs', 'options': 'rw,seclabel,relatime,attr2,inode64,logbufs=8,logbsize=32k,noquota', 'size_total': 18238930944, 'size_available': 14193164288, 'block_size': 4096, 'block_total': 4452864, 'block_available': 3465128, 'block_used': 987736, 'inode_total': 8910848, 'inode_available': 8802255, 'inode_used': 108593, 'uuid': 'f47a2833-0a96-42cc-aafa-172e34efff8a'}, {'mount': '/boot', 'device': '/dev/vda1', 'fstype': 'xfs', 'options': 'rw,seclabel,relatime,attr2,inode64,logbufs=8,logbsize=32k,noquota', 'size_total': 1063256064, 'size_available': 852586496, 'block_size': 4096, 'block_total': 259584, 'block_available': 208151, 'block_used': 51433, 'inode_total': 524288, 'inode_available': 523979, 'inode_used': 309, 'uuid': '3126f0dc-4e4d-457e-8102-1f6f7dadc43c'}]


Question: How can I access values from that dictionary ? Is it dictionary or list of dictionaries ?

Thanks in advance!

EDIT:

Thank you @Vladimir Botka.

Now situation looks like this: I have slightly prettified your example ( with human readable values) and I have values twice, like this. Is there a way to do it so that values are inserted into destination file only once ? I assume some if filter with list will be used here.

mount: / free space: 3.77 GB
mount: /boot free space: 200.91 MB
 
mount: / free space: 3.89 GB
mount: /boot free space: 200.91 MB

EDIT 2:

I have managed to fix repeating output of file system. In case if someone need it, nested loops solved the issue:

{% set slots = [] %}
{% set size = [] %}
{% set size2 = [] %}
{% for host in groups['test'] %}
        {% for i in hostvars[host]['ansible_facts']['mounts'] if i not in slots %}
                {{ slots.append(i.mount) }}
                {{ size.append((i.size_total - i.size_available )|human_readable ) }}
                {{ size2.append(i.size_total|human_readable ) }}

        {% endfor %}
{% endfor %}
Filesystem: {{ slots[0] }}       Size: {{ size2[0] }} / {{ size[0] }}
Filesystem: {{ slots[1] }}       Size: {{ size2[1] }} / {{ size[1] }}

CodePudding user response:

Try this

{% for host in groups['test'] %}
{% for i in hostvars[host]['ansible_facts']['mounts'] %}
mount: {{ i.mount }} size_total: {{ i.size_total }}
{% endfor %}
{% endfor %}
  • Related