---
# Tasks for setting up API server certificates using cert-manager

# Create a Certificate resource for the API server
- name: Create Certificate for API server
  kubernetes.core.k8s:
    state: present
    definition:
      apiVersion: cert-manager.io/v1
      kind: Certificate
      metadata:
        name: api-server-cert
        namespace: openshift-config
      spec:
        secretName: api-server-cert
        issuerRef:
          name: "{{ certificate_issuer | default('letsencrypt-prod') }}"
          kind: "{{ certificate_issuer_kind | default('ClusterIssuer') }}"
        dnsNames:
          - "api.{{ cluster_name }}.{{ cluster_region }}.container.mom"
        duration: 2160h # 90 days
        renewBefore: 360h # 15 days
    kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
    validate_certs: "{{ k8s_auth_params.validate_certs }}"

# Wait for the certificate to be issued (up to 5 minutes)
- name: Wait for API server certificate to be ready
  kubernetes.core.k8s_info:
    api_version: cert-manager.io/v1
    kind: Certificate
    name: api-server-cert
    namespace: openshift-config
    kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
    validate_certs: "{{ k8s_auth_params.validate_certs }}"
  register: api_cert_status
  until: api_cert_status.resources[0].status.conditions | selectattr('type', 'equalto', 'Ready') | selectattr('status', 'equalto', 'True') | list | length > 0
  retries: 30
  delay: 10
  ignore_errors: true

# Configure API server to use the certificate
- name: Configure API server to use cert-manager certificate
  kubernetes.core.k8s:
    state: present
    definition:
      apiVersion: config.openshift.io/v1
      kind: APIServer
      metadata:
        name: cluster
      spec:
        servingCerts:
          namedCertificates:
          - names:
            - "api.{{ cluster_name }}.{{ cluster_region }}.container.mom"
            servingCertificate:
              name: api-server-cert
    kubeconfig: "{{ k8s_auth_params.kubeconfig }}"
    validate_certs: "{{ k8s_auth_params.validate_certs }}"
