Ansible - Sort an array using the sort filter

sort is a Jinja2 filter, used to sort an array (also known as a list). Let's say you are using the vars plugin to create an array of integers, like this.

vars:
  integers: 
    - 20
    - 3
    - 1

 

Or the set_facts module, like this.

- set_fact:
    integers:
      - 20
      - 3
      - 1

 

The debug module can be used to output the entire array, like this.

- name: output the contents of the 'integers' array
  debug: 
    msg: "{{ integers }}"

 

Which should return the following. Notice the output is not sorted numerically.

TASK [output the contents of the 'integers' array]
ok: [server1.example.com] => {
    "msg": [
        "20",
        "3",
        "1"
    ]
}

 

The sort filter can be used to sort the list, like this.

- name: output the contents of the 'integers' array, sorted
  debug: 
    msg: "{{ integers | sort }}"

 

Which should return the following. Now the output is now sorted numerically.

TASK [output the contents of the 'integers' array, sorted]
ok: [server1.example.com] => {
    "msg": [
        "1",
        "3",
        "20"
    ]
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee

Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.





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