Somebody know how to sum numbers over loop in ansible and set to variable?
Following:
- set_fact:
total: "{{ sum(item | int) }}" <--- it's not work!!!
loop:
- 1
- 4
- 3
- debug: var=total
Thanks
Somebody know how to sum numbers over loop in ansible and set to variable?
Following:
- set_fact:
total: "{{ sum(item | int) }}" <--- it's not work!!!
loop:
- 1
- 4
- 3
- debug: var=total
Thanks
here is how to do it:
- set_fact:
total: "{{ total|default(0)|int + item|int }}"
loop:
- 1
- 4
- 3
- debug: var=total
by adding the default filter you dont need to declare (initialize to 0) the total variable in the vars section.
output:
PLAY [localhost] ****************************************************************************************************************************************************************************************************
TASK [set_fact] *****************************************************************************************************************************************************************************************************
ok: [localhost] => (item=1)
ok: [localhost] => (item=4)
ok: [localhost] => (item=3)
TASK [debug] ********************************************************************************************************************************************************************************************************
ok: [localhost] => {
"total": "8"
}
PLAY RECAP **********************************************************************************************************************************************************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0
hope it helps