'Ansible to consolidate service status on multiple servers

Below playbook works where inventory groups has multiple servers and to check the status of each service and display its status on console.

Problem is, I wanted to consolidate the status of each service on every server and send in an email, but it seems array (uistatus_app, uistatus_status, uistatus_print) gets re-initiated for each server run.

Is there any way where I can store the status in the global variable of each run and display?

for example:

server1: nginx is active

server1: PHP is active

server2: nginx is active

server2: PHP is unknown

Thanks.

- name: checking services
  shell: 'systemctl is-active {{item}}'
  with_items:
    - nginx
    - php74-php-fpm
  failed_when: false
  register: uistatus
  when: 'inventory_hostname in groups[''stg-ui]'
- name: get ui status in arrray
  set_fact:
    uistatus_app: '{{uistatus_app}}+[ ''{{item.item}}'']'
    uistatus_status: '{{uistatus_app}}+[ ''{{item.stdout}}'']'
  with_items: '{{ uistatus.results }}'
  when: 'inventory_hostname in groups[''stg-ui]'
- name: consolidate
  set_fact:
    uistatus_print: '{{uistatus_print}}+{{inventory_hostname}}: {{item[0]}} is item[1]}}]'
  loop: '{{ query(''together'',uistatus_app, uistatus.status }}'
  when: 'inventory_hostname in groups[''stg-ui]'


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source