# Sort hosts by gathered fact

**URL:** <https://forum.ansible.com/t/sort-hosts-by-gathered-fact/23450>\
**Category:** Ansible Project\
**Created:** [January 13, 2017, 10:15am UTC](https://forum.ansible.com/t/sort-hosts-by-gathered-fact/23450 "2017-01-13T10:15:17Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Alexander\_Brand](https://avatars.discourse-cdn.com/v4/letter/a/5daacb/32.png) [@Alexander\_Brand](https://forum.ansible.com/u/Alexander_Brand)\
**Post date:** [January 13, 2017, 10:15am UTC](https://forum.ansible.com/t/sort-hosts-by-gathered-fact/23450/1 "2017-01-13T10:15:17Z")

</div>

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
