---
- name: VSphere CSI Driver | Check vsphare credentials
  include_tasks: vsphere-credentials-check.yml

- name: VSphere CSI Driver | Generate CSI cloud-config
  template:
    src: "{{ item }}.j2"
    dest: "{{ kube_config_dir }}/{{ item }}"
    mode: "0640"
  with_items:
    - vsphere-csi-cloud-config
  when: inventory_hostname == groups['kube_control_plane'][0]

- name: VSphere CSI Driver | Generate Manifests
  template:
    src: "{{ item }}.j2"
    dest: "{{ kube_config_dir }}/{{ item }}"
    mode: "0644"
  with_items:
    - vsphere-csi-namespace.yml
    - vsphere-csi-driver.yml
    - vsphere-csi-controller-rbac.yml
    - vsphere-csi-node-rbac.yml
    - vsphere-csi-controller-config.yml
    - vsphere-csi-controller-deployment.yml
    - vsphere-csi-controller-service.yml
    - vsphere-csi-node.yml
  register: vsphere_csi_manifests
  when: inventory_hostname == groups['kube_control_plane'][0]

- name: VSphere CSI Driver | Apply Manifests
  kube:
    kubectl: "{{ bin_dir }}/kubectl"
    filename: "{{ kube_config_dir }}/{{ item.item }}"
    state: "latest"
  with_items:
    - "{{ vsphere_csi_manifests.results }}"
  when:
    - inventory_hostname == groups['kube_control_plane'][0]
    - not item is skipped
  loop_control:
    label: "{{ item.item }}"

- name: VSphere CSI Driver | Generate a CSI secret manifest
  command: "{{ kubectl }} create secret generic vsphere-config-secret --from-file=csi-vsphere.conf={{ kube_config_dir }}/vsphere-csi-cloud-config -n {{ vsphere_csi_namespace }} --dry-run --save-config -o yaml"
  register: vsphere_csi_secret_manifest
  when: inventory_hostname == groups['kube_control_plane'][0]
  no_log: "{{ not (unsafe_show_logs | bool) }}"

- name: VSphere CSI Driver | Apply a CSI secret manifest
  command:
    cmd: "{{ kubectl }} apply -f -"
    stdin: "{{ vsphere_csi_secret_manifest.stdout }}"
  when: inventory_hostname == groups['kube_control_plane'][0]
  no_log: "{{ not (unsafe_show_logs | bool) }}"
