---
- name: 修正Nomad节点的Consul角色配置
  hosts: nomad_nodes
  become: yes
  vars:
    consul_addresses: "master.tailnet-68f9.ts.net:8500,ash3c.tailnet-68f9.ts.net:8500,warden.tailnet-68f9.ts.net:8500"

  tasks:
    - name: 备份原始Nomad配置
      copy:
        src: /etc/nomad.d/nomad.hcl
        dest: /etc/nomad.d/nomad.hcl.bak_{{ ansible_date_time.iso8601 }}
        remote_src: yes

    - name: 检查节点角色
      shell: grep -A 1 "server {" /etc/nomad.d/nomad.hcl | grep "enabled = true" | wc -l
      register: is_server
      changed_when: false

    - name: 检查节点角色
      shell: grep -A 1 "client {" /etc/nomad.d/nomad.hcl | grep "enabled = true" | wc -l
      register: is_client
      changed_when: false

    - name: 修正服务器节点的Consul配置
      blockinfile:
        path: /etc/nomad.d/nomad.hcl
        marker: "# {mark} ANSIBLE MANAGED BLOCK - CONSUL CONFIG"
        block: |
          consul {
            address = "{{ consul_addresses }}"
            server_service_name = "nomad"
            client_service_name = "nomad-client"
            auto_advertise = true
            server_auto_join = true
            client_auto_join = false
          }
        replace: true
      when: is_server.stdout == "1"

    - name: 修正客户端节点的Consul配置
      blockinfile:
        path: /etc/nomad.d/nomad.hcl
        marker: "# {mark} ANSIBLE MANAGED BLOCK - CONSUL CONFIG"
        block: |
          consul {
            address = "{{ consul_addresses }}"
            server_service_name = "nomad"
            client_service_name = "nomad-client"
            auto_advertise = true
            server_auto_join = false
            client_auto_join = true
          }
        replace: true
      when: is_client.stdout == "1"

    - name: 重启Nomad服务
      systemd:
        name: nomad
        state: restarted
        enabled: yes
        daemon_reload: yes

    - name: 等待Nomad服务启动
      wait_for:
        port: 4646
        host: "{{ ansible_host }}"
        timeout: 30

    - name: 显示节点角色和配置
      debug:
        msg: "节点 {{ inventory_hostname }} 是 {{ '服务器' if is_server.stdout == '1' else '客户端' }} 节点，Consul配置已更新"

