---
- name: 修复 Nomad 服务器 region 配置
  hosts: nomad_servers
  become: yes
  vars:
    nomad_config_dir: /etc/nomad.d
  
  tasks:
    - name: 备份当前 Nomad 配置
      copy:
        src: "{{ nomad_config_dir }}/nomad.hcl"
        dest: "{{ nomad_config_dir }}/nomad.hcl.backup.{{ ansible_date_time.epoch }}"
        remote_src: yes
      ignore_errors: yes

    - name: 更新 Nomad 配置文件以添加 region 设置
      blockinfile:
        path: "{{ nomad_config_dir }}/nomad.hcl"
        insertafter: '^datacenter = '
        block: |
          region = "dc1"
        marker: "# {mark} Ansible managed region setting"
      notify: restart nomad

    - name: 更新节点名称以移除 .global 后缀（如果存在）
      replace:
        path: "{{ nomad_config_dir }}/nomad.hcl"
        regexp: 'name = "(.*)\.global(.*)"'
        replace: 'name = "\1\2"'
      notify: restart nomad

    - name: 确保 retry_join 使用正确的 IP 地址
      replace:
        path: "{{ nomad_config_dir }}/nomad.hcl"
        regexp: 'retry_join = \[(.*)\]'
        replace: 'retry_join = ["100.81.26.3", "100.103.147.94", "100.90.159.68", "100.116.158.95", "100.98.209.50", "100.120.225.29"]'
      notify: restart nomad

  handlers:
    - name: restart nomad
      systemd:
        name: nomad
        state: restarted