Ansible - Return the greatest value in array using the max filter

max is a Jinja2 filter, used to return the largest value in an array (also known as a list). The min filter is used to return the lowest value.Let's say you are using the vars plugin to create an array of integers.

vars:
  integers: 
    - 2
    - 4
    - 3
    - 1

 

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

- name: output the contents of the 'integers' array
  debug: 
    var: integers

 

Which should return the following.

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

 

The max filter can be used to get the largest value from the array.

- name: output the max value in the 'integers' array
  debug: 
    var: integers | max

 

Which should return the following.

TASK [output the max value in the 'integers' array]
ok: [server1.example.com] => {
    "integers | max": "4"
}

 



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 416e0 in the box below so that we can be sure you are a human.




Comments


June 21st, 2021 by Ari Prince
Hello here, am new to Ansible and i would like to learn on how to filter for info. my var debug is: ok: [localhost] => { "msg": { "changed": false, "msg": "All items completed", "results": [ { "ansible_loop_var": "item", "changed": false, "datastores": [ { "accessible": true, "capacity": 4397778075648, "datastore_cluster": "DATACLUSTER", "freeSpace": 1529958367232, "maintenanceMode": "normal", "multipleHostAccess": true, "name": "store-00", i would like to extract or get the "freeSpace" value. any help or reference would nice, sorry for the post

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |