---
- name: Verify Vault Cluster Status
  hosts: ch4,ash3c,warden
  become: yes
  
  tasks:
    - name: Check Vault service status
      systemd:
        name: vault
      register: vault_service_status

    - name: Display Vault service status
      debug:
        msg: "Vault service on {{ inventory_hostname }}: {{ vault_service_status.status.ActiveState }}"

    - name: Check Vault process
      shell: ps aux | grep vault | grep -v grep
      register: vault_process
      ignore_errors: yes

    - name: Display Vault process
      debug:
        msg: "Vault process on {{ inventory_hostname }}: {{ vault_process.stdout_lines }}"

    - name: Check Vault port 8200
      wait_for:
        port: 8200
        host: "{{ ansible_default_ipv4.address }}"
        timeout: 10
      register: vault_port_check
      ignore_errors: yes

    - name: Display port check result
      debug:
        msg: "Vault port 8200 on {{ inventory_hostname }}: {{ 'OPEN' if vault_port_check.failed == false else 'CLOSED' }}"

    - name: Get Vault status
      uri:
        url: "http://{{ ansible_default_ipv4.address }}:8200/v1/sys/health"
        method: GET
        status_code: [200, 429, 472, 473, 501, 503]
      register: vault_health
      ignore_errors: yes

    - name: Display Vault health status
      debug:
        msg: "Vault health on {{ inventory_hostname }}: {{ vault_health.json if vault_health.json is defined else 'Connection failed' }}"

    - name: Check Consul integration
      uri:
        url: "http://127.0.0.1:8500/v1/kv/vault/?recurse"
        method: GET
      register: consul_vault_kv
      ignore_errors: yes

    - name: Display Consul Vault KV
      debug:
        msg: "Consul Vault KV on {{ inventory_hostname }}: {{ 'Found vault keys' if consul_vault_kv.status == 200 else 'No vault keys found' }}"

    - name: Check Vault logs for errors
      shell: journalctl -u vault --no-pager -n 10 | grep -i error || echo "No errors found"
      register: vault_logs
      ignore_errors: yes

    - name: Display Vault error logs
      debug:
        msg: "Vault errors on {{ inventory_hostname }}: {{ vault_logs.stdout_lines }}"