---
- name: Initialize Vault Cluster
  hosts: ch4  # 只在一个节点初始化
  become: yes
  
  tasks:
    - name: Check if Vault is already initialized
      uri:
        url: "http://{{ ansible_host }}:8200/v1/sys/health"
        method: GET
        status_code: [200, 429, 472, 473, 501, 503]
      register: vault_health

    - name: Initialize Vault (only if not initialized)
      uri:
        url: "http://{{ ansible_host }}:8200/v1/sys/init"
        method: POST
        body_format: json
        body:
          secret_shares: 5
          secret_threshold: 3
        status_code: 200
      register: vault_init_result
      when: not vault_health.json.initialized

    - name: Save initialization results to local file
      copy:
        content: |
          # Vault Cluster Initialization Results
          Generated on: {{ ansible_date_time.iso8601 }}
          Initialized by: {{ inventory_hostname }}
          
          ## Root Token
          {{ vault_init_result.json.root_token }}
          
          ## Unseal Keys
          {% for key in vault_init_result.json.keys %}
          Key {{ loop.index }}: {{ key }}
          {% endfor %}
          
          ## Base64 Unseal Keys
          {% for key in vault_init_result.json.keys_base64 %}
          Key {{ loop.index }} (base64): {{ key }}
          {% endfor %}
          
          ## Important Notes
          - Store these keys securely and separately
          - You need 3 out of 5 keys to unseal Vault
          - Root token provides full access to Vault
          - Consider revoking root token after initial setup
        dest: /tmp/vault-init-results.txt
      delegate_to: localhost
      when: vault_init_result is defined and vault_init_result.json is defined

    - name: Display initialization results
      debug:
        msg: |
          Vault initialized successfully!
          Root Token: {{ vault_init_result.json.root_token }}
          Unseal Keys: {{ vault_init_result.json.keys }}
      when: vault_init_result is defined and vault_init_result.json is defined

    - name: Display already initialized message
      debug:
        msg: "Vault is already initialized on {{ inventory_hostname }}"
      when: vault_health.json.initialized