---
- name: Install NFS CSI Plugin for Nomad
  hosts: nomad_nodes
  become: yes
  vars:
    nomad_user: nomad
    nomad_plugins_dir: /opt/nomad/plugins
    csi_driver_version: "v4.0.0"
    csi_driver_url: "https://github.com/kubernetes-csi/csi-driver-nfs/releases/download/{{ csi_driver_version }}/csi-nfs-driver"

  tasks:
    - name: Stop Nomad service
      systemd:
        name: nomad
        state: stopped

    - name: Create plugins directory
      file:
        path: "{{ nomad_plugins_dir }}"
        state: directory
        owner: "{{ nomad_user }}"
        group: "{{ nomad_user }}"
        mode: '0755'

    - name: Download NFS CSI driver
      get_url:
        url: "{{ csi_driver_url }}"
        dest: "{{ nomad_plugins_dir }}/csi-nfs-driver"
        owner: "{{ nomad_user }}"
        group: "{{ nomad_user }}"
        mode: '0755'

    - name: Install required packages for CSI
      package:
        name: 
          - nfs-common
          - mount
        state: present

    - name: Create CSI mount directory
      file:
        path: /opt/nomad/csi
        state: directory
        owner: "{{ nomad_user }}"
        group: "{{ nomad_user }}"
        mode: '0755'

    - name: Update Nomad configuration for CSI plugin
      blockinfile:
        path: /etc/nomad.d/nomad.hcl
        marker: "# {mark} CSI PLUGIN CONFIGURATION"
        block: |
          plugin_dir = "{{ nomad_plugins_dir }}"

          plugin "csi-nfs" {
            type = "csi"
            config {
              driver_name = "nfs.csi.k8s.io"
              mount_dir = "/opt/nomad/csi"
              health_timeout = "30s"
              log_level = "INFO"
            }
          }
        insertafter: 'data_dir = "/opt/nomad/data"'

    - name: Start Nomad service
      systemd:
        name: nomad
        state: started
        enabled: yes

    - name: Wait for Nomad to start
      wait_for:
        port: 4646
        delay: 10
        timeout: 60

    - name: Check Nomad status
      command: nomad node status
      register: nomad_status
      ignore_errors: yes

    - name: Display Nomad status
      debug:
        var: nomad_status.stdout_lines






