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
JavaScript
x
17
17
1
ok: [127.0.0.1] => {
2
"msg": {
3
"master01.example.com": {
4
"cpu_total": 8,
5
"cpu_used": 0.22
6
},
7
"master02.example.com": {
8
"cpu_total": 8,
9
"cpu_used": 0.27
10
},
11
"master03.example.com": {
12
"cpu_total": 8,
13
"cpu_used": 0.22
14
}
15
}
16
}
17
I am trying something like this and struggling to devise a solution.
JavaScript
1
5
1
- name: Total section for master nodes
2
set_fact:
3
total_master: "{{ (total_master | default({}))| combine({ 'total_cpu' : total_cpu+(item.value.cpu_total|int) }) }} "
4
with_dict: "{{ master_nodes }}"
5
What I am trying achieve in total_master
JavaScript
1
7
1
ok: [127.0.0.1] => {
2
"msg": {
3
"total_cpu": 24,
4
"total_used_cpu": 0.71
5
}
6
}
7
Advertisement
Answer
This could be one option:
JavaScript
1
9
1
- set_fact:
2
result: "{{ result | default({}) | combine({ item: master_nodes | json_query('@.*') | sum(attribute=item)}) }}"
3
loop:
4
- cpu_total
5
- cpu_used
6
7
- debug:
8
var: result
9
gives
JavaScript
1
5
1
ok: [localhost] =>
2
result:
3
cpu_total: 24
4
cpu_used: 0.71
5
Another flavour,
JavaScript
1
9
1
- set_fact:
2
result: "{{ {
3
'total_cpu': master_nodes | json_query('@.*.cpu_total') | sum(),
4
'total_cpu_used': master_nodes | json_query('@.*.cpu_used') | sum()
5
} }}"
6
7
- debug:
8
var: result
9
gives
JavaScript
1
5
1
ok: [localhost] =>
2
result:
3
total_cpu: 24
4
total_cpu_used: 0.71
5