---

- name: Cert Manager | Remove legacy addon dir and manifests
  file:
    path: "{{ kube_config_dir }}/addons/cert_manager"
    state: absent
  when:
    - inventory_hostname == groups['kube_control_plane'][0]
  tags:
    - upgrade

- name: Cert Manager | Remove legacy namespace
  command: >
    {{ kubectl }} delete namespace {{ cert_manager_namespace }}
  ignore_errors: true  # noqa ignore-errors
  when:
    - inventory_hostname == groups['kube_control_plane'][0]
  tags:
    - upgrade

- name: Cert Manager | Create addon dir
  file:
    path: "{{ kube_config_dir }}/addons/cert_manager"
    state: directory
    owner: root
    group: root
    mode: "0755"
  when:
    - inventory_hostname == groups['kube_control_plane'][0]

- name: Cert Manager | Templates list
  set_fact:
    cert_manager_templates:
      - { name: cert-manager, file: cert-manager.yml, type: all }
      - { name: cert-manager.crds, file: cert-manager.crds.yml, type: crd }

- name: Cert Manager | Create manifests
  template:
    src: "{{ item.file }}.j2"
    dest: "{{ kube_config_dir }}/addons/cert_manager/{{ item.file }}"
    mode: "0644"
  with_items: "{{ cert_manager_templates }}"
  register: cert_manager_manifests
  when:
    - inventory_hostname == groups['kube_control_plane'][0]

- name: Cert Manager | Apply manifests
  kube:
    name: "{{ item.item.name }}"
    kubectl: "{{ bin_dir }}/kubectl"
    resource: "{{ item.item.type }}"
    filename: "{{ kube_config_dir }}/addons/cert_manager/{{ item.item.file }}"
    state: "latest"
  with_items: "{{ cert_manager_manifests.results }}"
  when:
    - inventory_hostname == groups['kube_control_plane'][0]
