---
- name: Kubernetes Apps | Wait for kube-apiserver
  uri:
    url: "{{ kube_apiserver_endpoint }}/healthz"
    validate_certs: false
    client_cert: "{{ kube_apiserver_client_cert }}"
    client_key: "{{ kube_apiserver_client_key }}"
  register: result
  until: result.status == 200
  retries: 20
  delay: 1
  when: inventory_hostname == groups['kube_control_plane'][0]

- name: Kubernetes Apps | CoreDNS
  command:
    cmd: "{{ kubectl_apply_stdin }}"
    stdin: "{{ lookup('template', item) }}"
  delegate_to: "{{ groups['kube_control_plane'][0] }}"
  run_once: true
  loop: "{{ coredns_manifests | flatten }}"
  tags:
    - coredns
  vars:
    clusterIP: "{{ skydns_server }}"
  when:
    - dns_mode in ['coredns', 'coredns_dual']
    - deploy_coredns

- name: Kubernetes Apps | CoreDNS Secondary
  command:
    cmd: "{{ kubectl_apply_stdin }}"
    stdin: "{{ lookup('template', item) }}"
  delegate_to: "{{ groups['kube_control_plane'][0] }}"
  run_once: true
  loop: "{{ coredns_manifests | flatten }}"
  tags:
    - coredns
  vars:
    clusterIP: "{{ skydns_server_secondary }}"
    coredns_ordinal_suffix: "-secondary"
  when:
    - dns_mode == 'coredns_dual'
    - deploy_coredns

- name: Kubernetes Apps | nodelocalDNS
  command:
    cmd: "{{ kubectl_apply_stdin }}"
    stdin: "{{ lookup('template', item) }}"
  delegate_to: "{{ groups['kube_control_plane'][0] }}"
  run_once: true
  loop: "{{ nodelocaldns_manifests | flatten }}"
  when:
    - enable_nodelocaldns
  tags:
    - nodelocaldns
    - coredns
  vars:
    primaryClusterIP: >-
      {%- if dns_mode in ['coredns', 'coredns_dual'] -%}
      {{ skydns_server }}
      {%- elif dns_mode == 'manual' -%}
      {{ manual_dns_server }}
      {%- endif -%}
    secondaryclusterIP: "{{ skydns_server_secondary }}"
    forwardTarget: >-
      {%- if secondaryclusterIP is defined and dns_mode == 'coredns_dual' -%}
      {{ primaryClusterIP }} {{ secondaryclusterIP }}
      {%- else -%}
      {{ primaryClusterIP }}
      {%- endif -%}
    upstreamForwardTarget: >-
      {%- if upstream_dns_servers | length > 0 -%}
      {{ upstream_dns_servers | join(' ') }}
      {%- else -%}
      /etc/resolv.conf
      {%- endif -%}

- name: Kubernetes Apps | Etcd metrics endpoints
  command:
    cmd: "{{ kubectl_apply_stdin }}"
    stdin: "{{ lookup('template', item) }}"
  delegate_to: "{{ groups['kube_control_plane'][0] }}"
  run_once: true
  loop:
    - etcd_metrics-endpoints.yml.j2
    - etcd_metrics-service.yml.j2
  when: etcd_metrics_port is defined and etcd_metrics_service_labels is defined
  tags:
    - etcd_metrics
