Max filter for list in Ansible - works up to 9?

Viewed 37

I'm using max filter to find the maximum number in the ansible list. If I have a list with just a numbers from 1-10, from some reason max gives me 9 as the maximum number? What could be the problem here?

Here is the code I used

- name: Find the maximum number from the list1
  set_fact:  
    ds_max_number: "{{ list1 | max }}"
1 Answers

According the documentation Builtin Filters - max()

Return the largest item from the sequence.

{{ [1, 2, 3]|max }}
    -> 3

and a short test

---
- hosts: localhost
  become: false
  gather_facts: false

  tasks:

  - name: Show max
    debug:
      msg: "{{ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | max }}" # contains list of integers

I am not able to produce an issue.

TASK [Show max] **
ok: [localhost] =>
  msg: '10'

What could be the problem here?

Probably the definition and content of your list.


Regarding your comments and new question about "list of strings" instead of "list of integers"

... these are strings. How to convert them to int?

you may have a look into the following approach

---
- hosts: localhost
  become: false
  gather_facts: false

  vars:

    LIST: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"] # of strings

  tasks:

  - name: Show max (str)
    debug:
      msg: "{{ LIST | max }}"

  - name: Show max (int)
    debug:
      msg: "{{ LIST | map('int') | max }}"

resulting into an output of

TASK [Show max (str)] **
ok: [localhost] =>
  msg: '9'

TASK [Show max (int)] **
ok: [localhost] =>
  msg: '10'

Further Documentation

  • Data manipulation

    map: this is a basic for loop that just allows you to change every item in a list, using the ‘attribute’ keyword you can do the transformation based on attributes of the list elements.

  • Builtin Filters - map()

Thanks to

Reason for the behavior

  • Ansible - Check max number list

    You are comparing your values as string so the result is totally expected. "90" (starts with 9) is further in the alphabet than "130" (starts with 1). You need to compare as int to get the greater int value.

Related