Is there a shortcut to sum the contents of a list in ansible?

Viewed 1717

I have a list sList as:

sList = ['12','8','10']

I need the sum of all the elements of sList.
I came across sum() function in jinja2 but it takes attributes etc, and not sure how to use it with a list.
I tried:

- set_fact:
    sList:
      - '12'
      - '8'
      - '10'

- set_fact:
    sumList: "{{ sum(sList) }}" 

- debug: var=sumList

Expected result: sumList = 30, but gets below error:

"msg": "The task includes an option with an undefined variable. The error was: 'sum' is undefined 

Please help.

Thanks

1 Answers

The filter sum "Returns the sum of a sequence of numbers". The variable sList is a list of strings. The task below will fail

    - set_fact:
        sList: ['12', '8', '10']
    - set_fact:
        sumList: "{{ sList|sum }}"

fatal: [localhost]: FAILED! => msg: 'Unexpected templating type error occurred on ({{ sList|sum }}): unsupported operand type(s) for +: ''int'' and ''AnsibleUnicode'''

To solve the problem, use a list of numbers. For example

    - set_fact:
        sList: [12, 8, 10]
    - set_fact:
        sumList: "{{ sList|sum }}"
    - debug:
        var: sumList

give

  sumList: '30'

The next option is to convert the items of the list to numbers. Map either int or float function. For example

    - set_fact:
        sList: ['12', '8', '10']

    - set_fact:
        sumList: "{{ sList|map('int')|sum }}"
    - debug:
        var: sumList

    - set_fact:
        sumList: "{{ sList|map('float')|sum }}"
    - debug:
        var: sumList

give

  sumList: '30'

  sumList: '30.0'
Related