---
# Ansible Playbook: 部署 Consul Client 到所有 Nomad 节点
- name: Deploy Consul Client to Nomad nodes
  hosts: nomad_clients:nomad_servers
  become: yes
  vars:
    consul_version: "1.21.5"
    consul_datacenter: "dc1"
    consul_servers:
      - "100.117.106.136:8300"  # master (韩国)
      - "100.122.197.112:8300"  # warden (北京)
      - "100.116.80.94:8300"    # ash3c (美国)
    
  tasks:
    - name: Update APT cache (忽略 GPG 错误)
      apt:
        update_cache: yes
        force_apt_get: yes
      ignore_errors: yes

    - name: Install consul via APT (假设源已存在)
      apt:
        name: consul={{ consul_version }}-*
        state: present
        force_apt_get: yes
      ignore_errors: yes

    - name: Create consul user (if not exists)
      user:
        name: consul
        system: yes
        shell: /bin/false
        home: /opt/consul
        create_home: yes

    - name: Create consul directories
      file:
        path: "{{ item }}"
        state: directory
        owner: consul
        group: consul
        mode: '0755'
      loop:
        - /opt/consul
        - /opt/consul/data
        - /etc/consul.d
        - /var/log/consul

    - name: Get node Tailscale IP
      shell: ip addr show tailscale0 | grep 'inet ' | awk '{print $2}' | cut -d'/' -f1
      register: tailscale_ip
      failed_when: tailscale_ip.stdout == ""

    - name: Create consul client configuration
      template:
        src: templates/consul-client.hcl.j2
        dest: /etc/consul.d/consul.hcl
        owner: consul
        group: consul
        mode: '0644'
      notify: restart consul

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

    - name: Enable and start consul service
      systemd:
        name: consul
        enabled: yes
        state: started
      notify: restart consul

    - name: Wait for consul to be ready
      uri:
        url: "http://{{ tailscale_ip.stdout }}:8500/v1/status/leader"
        status_code: 200
        timeout: 5
      register: consul_leader_status
      until: consul_leader_status.status == 200
      retries: 30
      delay: 5

    - name: Verify consul cluster membership
      shell: consul members -status=alive -format=json | jq -r '.[].Name'
      register: consul_members
      changed_when: false

    - name: Display cluster status
      debug:
        msg: "Node {{ inventory_hostname.split('.')[0] }} joined cluster with {{ consul_members.stdout_lines | length }} members"

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

    - name: restart consul
      systemd:
        name: consul
        state: restarted