Ansible to consolidate service status on multiple servers

Viewed 572

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]'
1 Answers

Set the variable with the list of the statuses in each host, e.g.

- hosts: all
  tasks:
    - name: checking services
      command: "echo {{ item }} is active"
      loop:
        - nginx
        - php74-php-fpm
      failed_when: False
      register: uistatus
      when: inventory_hostname in groups.stg_ui
    - set_fact:
        my_services: "{{ uistatus.results|default([])|
                         map(attribute='stdout')|
                         list }}"
    - debug:
        var: my_services

gives

ok: [server1] => 
  my_services:
  - nginx is active
  - php74-php-fpm is active
ok: [server2] => 
  my_services:
  - nginx is active
  - php74-php-fpm is active

Then run_once, extract the lists and create the dictionary all_services, e.g.

    - set_fact:
        all_services: "{{ dict(ansible_play_hosts|zip(stats)) }}"
      vars:
        stats: "{{ ansible_play_hosts|
                   map('extract', hostvars, 'my_services')|
                   list }}"
      run_once: true
    - debug:
        var: all_services
      run_once: true

gives

ok: [server1] => 
  all_services:
    server1:
    - nginx is active
    - php74-php-fpm is active
    server2:
    - nginx is active
    - php74-php-fpm is active

The dictionary is available to all hosts in the playbook.

Related