---
- name: Check kubelet serving certificates approved with kubelet_csr_approver
  when:
  - kubelet_rotate_server_certificates | default(false)
  - kubelet_csr_approver_enabled | default(kubelet_rotate_server_certificates | default(false))
  vars:
    csrs: "{{ csr_json.stdout | from_json }}"
  block:

  - name: Get certificate signing requests
    command: "{{ bin_dir }}/kubectl get csr -o jsonpath-as-json={.items[*]}"
    register: csr_json
    changed_when: false

  - name: Check there are csrs
    assert:
      that: csrs | length > 0
      fail_msg: kubelet_rotate_server_certificates is {{ kubelet_rotate_server_certificates }} but no csr's found

  - name: Check there are Denied/Pending csrs
    assert:
      that:
      - csrs | rejectattr('status') | length == 0 # Pending == no status
      - csrs | map(attribute='status.conditions') | flatten | selectattr('type', 'equalto', 'Denied') | length == 0 # Denied

      fail_msg: kubelet_csr_approver is enabled but CSRs are not approved

- name: Approve kubelet serving certificates
  when:
  - kubelet_rotate_server_certificates | default(false)
  - not (kubelet_csr_approver_enabled | default(kubelet_rotate_server_certificates | default(false)))
  block:

  - name: Get certificate signing requests
    command: "{{ bin_dir }}/kubectl get csr -o name"
    register: get_csr
    changed_when: false

  - name: Check there are csrs
    assert:
      that: get_csr.stdout_lines | length > 0
      fail_msg: kubelet_rotate_server_certificates is {{ kubelet_rotate_server_certificates }} but no csr's found

  - name: Approve certificates
    command: "{{ bin_dir }}/kubectl certificate approve {{ get_csr.stdout_lines | join(' ') }}"
    register: certificate_approve
    when: get_csr.stdout_lines | length > 0
    changed_when: certificate_approve.stdout
