ce7e2bc205
Claude-Session: https://claude.ai/code/session_01JEczyvRjfakkiDNkbZA7PR
83 lines
2.7 KiB
YAML
83 lines
2.7 KiB
YAML
---
|
|
# Verifies the critical services listed per host in the inventory
|
|
# (critical_services) and optionally starts any that are stopped.
|
|
#
|
|
# Extra vars (optional):
|
|
# restart_stopped - default false; when true, start services found stopped
|
|
|
|
- name: Check Host Availability
|
|
hosts: ubuntu:rocky
|
|
gather_facts: false
|
|
ignore_unreachable: true
|
|
|
|
tasks:
|
|
- name: Ping hosts to check availability
|
|
ansible.builtin.ping:
|
|
register: ping_result
|
|
ignore_errors: true
|
|
ignore_unreachable: true
|
|
|
|
- name: Add reachable hosts to group
|
|
ansible.builtin.group_by:
|
|
key: reachable_hosts
|
|
when: ping_result is succeeded
|
|
|
|
- name: Report offline hosts
|
|
ansible.builtin.debug:
|
|
msg: "{{ inventory_hostname }} - OFFLINE"
|
|
when: ping_result is not succeeded
|
|
delegate_to: localhost
|
|
|
|
- name: Service Check
|
|
hosts: reachable_hosts
|
|
become: true
|
|
gather_facts: false
|
|
|
|
vars:
|
|
restart_stopped: false
|
|
|
|
tasks:
|
|
- name: Gather service facts
|
|
ansible.builtin.service_facts:
|
|
|
|
- name: Evaluate critical services
|
|
ansible.builtin.set_fact:
|
|
service_states: >-
|
|
{{ service_states | default([])
|
|
+ [{'name': item, 'state': (ansible_facts.services[item ~ '.service'].state | default('not-found'))}] }}
|
|
loop: "{{ critical_services | default([]) }}"
|
|
|
|
- name: Print report
|
|
ansible.builtin.debug:
|
|
msg: |
|
|
======================================================
|
|
HOST: {{ inventory_hostname }} ({{ ansible_host }})
|
|
======================================================
|
|
{% if service_states | default([]) | length == 0 %}
|
|
no critical services defined in inventory
|
|
{% else %}
|
|
{% for svc in service_states %}
|
|
{{ '%-24s' | format(svc.name) }} {{ 'RUNNING' if svc.state == 'running' else ('NOT FOUND' if svc.state == 'not-found' else svc.state | upper) }}
|
|
{% endfor %}
|
|
{% endif %}
|
|
======================================================
|
|
|
|
- name: Warn on services that are not running
|
|
ansible.builtin.debug:
|
|
msg: "WARNING: {{ item.name }} is {{ 'not installed' if item.state == 'not-found' else item.state }} on {{ inventory_hostname }}"
|
|
loop: "{{ service_states | default([]) }}"
|
|
loop_control:
|
|
label: "{{ item.name }}"
|
|
when: item.state != 'running'
|
|
|
|
- name: Start stopped services
|
|
ansible.builtin.service:
|
|
name: "{{ item.name }}"
|
|
state: started
|
|
loop: "{{ service_states | default([]) }}"
|
|
loop_control:
|
|
label: "{{ item.name }}"
|
|
when:
|
|
- restart_stopped | bool
|
|
- item.state not in ['running', 'not-found']
|