---

### tags:
###   cert-manager

- name: "Create namespace>"
  become: yes
  kubernetes.core.k8s:
    name: "{{ k8s_certmanager_helm__release_namespace }}"
    api_version: v1
    kind: Namespace
    state: present
  when:
  - inventory_hostname == groups['kube_control_plane'][0]
  tags:
    - namespace

- name: Create secret for digitalocean-dns
  become: yes
  kubernetes.core.k8s:
    definition:
      api_version: v1
      kind: Secret
      metadata:
        namespace: "{{ k8s_certmanager_helm__release_namespace | default('cert-manager') }}"
        name: digitalocean-dns
      type: Opaque
      data:
        access-token: "{{ digitalocean_authentication_token | string | b64encode }}"
  when: 
  - inventory_hostname == groups['kube_control_plane'][0]
  tags:
    - cert-manager

- name: "Install cert-manager"
  block:

  - name: Install cert-manager via helm
    become: yes
    kubernetes.core.helm:
      create_namespace: yes
      name: "{{ k8s_certmanager_helm__chart_ref }}"
      chart_ref: "{{ k8s_certmanager_helm__chart_ref }}"
      chart_repo_url: "{{ k8s_certmanager_helm__chart_repo_url }}"
      chart_version: v1.9.1
      release_namespace: "{{ k8s_certmanager_helm__release_namespace }}"
      release_values: "{{ k8s_certmanager_helm__release_values }}"

  - name: Create ClusterIssuer for letsencrypt (prod/staging) with dns challenge
    become: yes
    kubernetes.core.k8s:
      definition:
        api_version: cert-manager.io/v1
        kind: ClusterIssuer
        metadata:
          name: "letsencrypt-{{ item.key }}"
        spec:
          acme:
            email: "{{ item.value.email }}"
            server: "{{ item.value.server }}"
            privateKeySecretRef:
              name: issuer-account-key
            solvers:
            - dns01:
                digitalocean:
                  tokenSecretRef:
                    name: digitalocean-dns
                    key: access-token
              selector:
                dnsZones:
                - 'smardigo.digital'
    loop: "{{ k8s_certmanager_helm__cluster_issuers_dns01 | dict2items }}"

  - name: Create ClusterIssuer for letsencrypt (prod/staging) with http challenge
    become: yes
    kubernetes.core.k8s:
      definition:
        api_version: cert-manager.io/v1
        kind: ClusterIssuer
        metadata:
          name: "letsencrypt-{{ item.key }}"
        spec:
          acme:
            email: "{{ item.value.email }}"
            server: "{{ item.value.server }}"
            privateKeySecretRef:
              name: issuer-account-key
            solvers:
            - http01:
                ingress:
                  class: nginx
    loop: "{{ k8s_certmanager_helm__cluster_issuers_http | dict2items }}"

  # end of block statement
  when: 
  - inventory_hostname == groups['kube_control_plane'][0]
  tags:
    - cert-manager
