Ansible - Return the greatest value in array using the max filter
by
Jeremy Canfield |
Updated: March 01 2023
| Ansible articles
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"
}
Did you find this article helpful?
If so, consider buying me a coffee over at
Comments
June 21 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