Bootstrap FreeKB - Ansible - Sort a list or dictionary using the sort filter
Ansible - Sort a list or dictionary using the sort filter

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


Please enter f03b10 in the box below so that we can be sure you are a human.