---
- name: Remove Consul configuration from Nomad servers
  hosts: semaphore,ash1d,ash2e,ch2,ch3,onecloud1,de
  become: yes
  
  tasks:
    - name: Remove entire Consul configuration block
      blockinfile:
        path: /etc/nomad.d/nomad.hcl
        marker: "# {mark} ANSIBLE MANAGED CONSUL CONFIG"
        state: absent

    - name: Remove Consul configuration lines
      lineinfile:
        path: /etc/nomad.d/nomad.hcl
        regexp: '^consul \{'
        state: absent

    - name: Remove Consul configuration content
      lineinfile:
        path: /etc/nomad.d/nomad.hcl
        regexp: '^  address ='
        state: absent

    - name: Remove Consul service names
      lineinfile:
        path: /etc/nomad.d/nomad.hcl
        regexp: '^  server_service_name ='
        state: absent

    - name: Remove Consul client service name
      lineinfile:
        path: /etc/nomad.d/nomad.hcl
        regexp: '^  client_service_name ='
        state: absent

    - name: Remove Consul auto-advertise
      lineinfile:
        path: /etc/nomad.d/nomad.hcl
        regexp: '^  auto_advertise ='
        state: absent

    - name: Remove Consul server auto-join
      lineinfile:
        path: /etc/nomad.d/nomad.hcl
        regexp: '^  server_auto_join ='
        state: absent

    - name: Remove Consul client auto-join
      lineinfile:
        path: /etc/nomad.d/nomad.hcl
        regexp: '^  client_auto_join ='
        state: absent

    - name: Remove Consul closing brace
      lineinfile:
        path: /etc/nomad.d/nomad.hcl
        regexp: '^}'
        state: absent

    - name: Restart Nomad service
      systemd:
        name: nomad
        state: restarted

    - name: Wait for Nomad to be ready
      wait_for:
        port: 4646
        host: "{{ ansible_default_ipv4.address }}"
        delay: 5
        timeout: 30

    - name: Display completion message
      debug:
        msg: "Removed Consul configuration from {{ inventory_hostname }}"
