Sort hosts by gathered fact

Is it possible to sort the hosts by a given fact? The use case is producing a list of machine name → free disk space with the top N machines that have the most free disk space.

The hosts need to be sorted by a fact, and not their name, otherwise something like this would work:

{% for host in groups['someGroup']|sort()%}{{ host }}{% endfor %}

I have tried a couple of things, but haven’t been able to get it to work:

`

Errors with ansible.inventory.host.Host object’ has no attribute ‘disk_free_space_bytes’

{% for host in hostvars|sort(attribute=‘disk_free_space_bytes’) %}{{ host }}: {{host.disk_free_space_bytes}}{% endfor %}

Doesn’t look like facts are part of vars

{% for host in hostvars|sort(attribute=‘vars.disk_free_space_bytes’) %}{{ host }}: {{host.disk_free_space_bytes}}{% endfor %}

This is close, but I lose the host

{% for val in groups[‘storage’]|map(‘extract’, hostvars, ‘disk_free_space_bytes’) %}

`

Any ideas if it’s possible to do this?

Thanks