Skip to content
Advertisement

Ansible: Add values in nested dictionary among them selves and insert into another dictionary

I am iterating over the following dictionary of dictionaries and want to add the values of nested dictionary and insert them into another dictionary.

master_nodes

ok: [127.0.0.1] => {
    "msg": {
        "master01.example.com": {
            "cpu_total": 8,
            "cpu_used": 0.22
        },
        "master02.example.com": {
            "cpu_total": 8,
            "cpu_used": 0.27
        },
        "master03.example.com": {
            "cpu_total": 8,
            "cpu_used": 0.22
        }
    }
}

I am trying something like this and struggling to devise a solution.

- name: Total section for master nodes
  set_fact:
    total_master: "{{ (total_master | default({}))| combine({ 'total_cpu' : total_cpu+(item.value.cpu_total|int) }) }} "
  with_dict: "{{ master_nodes }}"

What I am trying achieve in total_master

ok: [127.0.0.1] => {
    "msg": {
        "total_cpu": 24,
        "total_used_cpu": 0.71
    }
}

Advertisement

Answer

This could be one option:

- set_fact:
    result: "{{ result | default({}) | combine({ item: master_nodes | json_query('@.*') | sum(attribute=item)}) }}"
  loop:
    - cpu_total
    - cpu_used

- debug: 
    var: result

gives

ok: [localhost] => 
  result:
    cpu_total: 24
    cpu_used: 0.71

Another flavour,

- set_fact:
    result: "{{ { 
        'total_cpu': master_nodes | json_query('@.*.cpu_total') | sum(),
        'total_cpu_used': master_nodes | json_query('@.*.cpu_used') | sum()
      } }}"

- debug: 
    var: result

gives

ok: [localhost] => 
  result:
    total_cpu: 24
    total_cpu_used: 0.71
Advertisement