---
- name: Deploy Vault Cluster with Consul Integration
  hosts: ch4,ash3c,warden
  become: yes
  vars:
    vault_version: "1.15.2"
    vault_datacenter: "dc1"
    vault_cluster_name: "vault-cluster"
    
  tasks:
    - name: Update apt cache
      apt:
        update_cache: yes
        cache_valid_time: 3600

    - name: Add HashiCorp GPG key (if not exists)
      shell: |
        if [ ! -f /etc/apt/sources.list.d/hashicorp.list ]; then
          curl -fsSL https://apt.releases.hashicorp.com/gpg | gpg --dearmor | sudo tee /usr/share/keyrings/hashicorp-archive-keyring.gpg
          echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
        fi
      args:
        creates: /etc/apt/sources.list.d/hashicorp.list

    - name: Install Vault
      apt:
        name: vault
        state: present
        update_cache: yes
        allow_downgrade: yes

    - name: Create vault user and directories
      block:
        - name: Create vault data directory
          file:
            path: /opt/vault/data
            state: directory
            owner: vault
            group: vault
            mode: '0755'

        - name: Create vault config directory
          file:
            path: /etc/vault.d
            state: directory
            owner: vault
            group: vault
            mode: '0755'

    - name: Generate Vault configuration
      template:
        src: vault.hcl.j2
        dest: /etc/vault.d/vault.hcl
        owner: vault
        group: vault
        mode: '0640'
      notify: restart vault

    - name: Create Vault systemd service
      template:
        src: vault.service.j2
        dest: /etc/systemd/system/vault.service
        owner: root
        group: root
        mode: '0644'
      notify:
        - reload systemd
        - restart vault

    - name: Enable and start Vault service
      systemd:
        name: vault
        enabled: yes
        state: started
        daemon_reload: yes

  handlers:
    - name: reload systemd
      systemd:
        daemon_reload: yes

    - name: restart vault
      systemd:
        name: vault
        state: restarted