-1

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

  • In what way is it not working? Are you getting the wrong value, or are you getting an error message? – larsks May 26 '18 at 13:17
  • 2.5.1 Ansible has a known bug with `set_fact` module and loops. this is why my answer is not working for you. in case you interested you can check [here](https://stackoverflow.com/questions/49983209/ansible-cannot-append-into-a-list-in-a-with-items-loop) about the bug. – ilias-sp May 26 '18 at 14:39

1 Answers1

6

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

ilias-sp
  • 6,135
  • 4
  • 28
  • 41