Ansible - Sort a list or dictionary using the sort filter
by
Jeremy Canfield |
Updated: January 16 2024
| Ansible articles
sort is a Jinja filter used to sort a list or sort a dictionary. Let's say you are using the vars plugin to create a list of integers, like this.
---
- hosts: localhost
vars:
integers:
- 3
- 20
- 1
tasks:
- debug:
var: integers
...
Something like this should be returned. Notice the output is not sorted.
ok: [localhost] => {
"integers": [
"3",
"20",
"1"
]
}
The sort filter can be used to sort the list, like this.
---
- hosts: localhost
vars:
integers:
- 20
- 3
- 1
tasks:
- debug:
var: integers | sort
...
Which should return the following. Now the output is sorted numerically.
ok: [localhost] => {
"integers | sort": [
"1",
"3",
"20"
]
}
reverse can be used to sort the list in reverse order.
---
- hosts: localhost
vars:
integers:
- 20
- 3
- 1
tasks:
- debug:
var: integers | sort(reverse=true)
...
Did you find this article helpful?
If so, consider buying me a coffee over at