You say you:
firewalls: [hostA, hostB, hostC, hostD, hostE]
- have 5 separate files, e.g.
shell> find . -name '*_file'
./hostA_file
./hostD_file
./hostB_file
./hostC_file
./hostE_file
storing returned strings, e.g.
shell> cat *_file
vpn name : 2345 : 2022098 : 4567 : 590
vpn name : 1234 : 2022098 : 4567 : 590
vpn name : 1231 : 2022098 : 4567 : 590
vpn name : 3567 : 2022098 : 4567 : 590
vpn name : 5678 : 2022098 : 4567 : 590
- want only the active VPN count
- shell: "awk '{print $4}' {{ hostname }}_file"
which returns:
2345
1234
1231
3567
5678
Q: "I want the sum of these 5 values."
A: Get the active VPN counts in a loop. Declare the variables
firewalls: [hostA, hostB, hostC, hostD, hostE]
active_vpn_counts: "{{ count.results|map(attribute='stdout')|
map('int')|list }}"
The task below
- name: get active
command:
cmd: "awk '{print $4}' {{ item }}_file"
chdir: "{{ playbook_dir }}"
register: count
loop: "{{ firewalls }}"
gives
active_vpn_counts:
- 2345
- 1234
- 1231
- 3567
- 5678
sum the items. Declare the variable
active_vpn_sum: "{{ count.results|map(attribute='stdout')|
map('int')|sum }}"
gives
active_vpn_sum: '14055'
Notes
shell> tree .
.
├── ansible.cfg
├── hostA_file
├── hostB_file
├── hostC_file
├── hostD_file
├── hostE_file
├── hosts
└── pb.yml
0 directories, 8 files
- Example of a complete playbook for testing
shell> cat pb.yml
- hosts: localhost
vars:
firewalls: [hostA, hostB, hostC, hostD, hostE]
active_vpn_counts: "{{ count.results|map(attribute='stdout')|
map('int')|list }}"
active_vpn_sum: "{{ count.results|map(attribute='stdout')|
map('int')|sum }}"
tasks:
- name: get active
command:
cmd: "awk '{print $4}' {{ item }}_file"
chdir: "{{ playbook_dir }}"
register: count
loop: "{{ firewalls }}"
- debug:
var: active_vpn_counts
run_once: true
- debug:
var: active_vpn_sum
run_once: true