---
- name: Check kubernetes if installed
  ignore_errors: true
  command: kubectl get node --field-selector metadata.name={{ .hostname }}
  register: kube_node_info_important

- include_tasks: install_binaries.yaml

- include_tasks: deploy_kube_vip.yaml
  when:
    - .kubernetes.kube_vip.enabled
    - .groups.kube_control_plane | default list | has .inventory_name

- name: Select init kubernetes node
  run_once: true
  set_fact:
    init_kubernetes_node: |
      {{ index .inventory_hosts (.groups.kube_control_plane | default list | first) "hostname" }}

- name: Init kubernetes
  when: eq .hostname .init_kubernetes_node
  block:
    - include_tasks: init_kubernetes.yaml
      when: .kube_node_info_important.stderr | ne ""
    - include_tasks: deploy_cluster_dns.yaml
    - name: Fetch kubeconfig to local
      fetch:
        src: /etc/kubernetes/admin.conf
        dest: |
          {{ .work_dir }}/kubekey/kubeconfig
    - name: Generate certificate key by kubeadm
      command: |
        /usr/local/bin/kubeadm init phase upload-certs --upload-certs --config /etc/kubernetes/kubeadm-config.yaml 2>&1 \
          | awk '/Using certificate key:/{getline; print}'
      register: kubeadm_cert_result
    - name: Set_Fact certificate key to all hosts
      set_fact:
        kubeadm_cert: |
          {{ .kubeadm_cert_result.stdout }}
    - name: Generate kubeadm token
      block:
        - name: Generate token by kubeadm
          command: /usr/local/bin/kubeadm token create
          register: kubeadm_token_result
        - name: Set_Fact token to all hosts
          set_fact:
            kubeadm_token: |
              {{ .kubeadm_token_result.stdout }}
    - name: Set_Fact init endpoint
      set_fact:
        init_kubernetes_endpoint: |
          {{ .inventory_name }}

- include_tasks: join_kubernetes.yaml
  when:
    - .kube_node_info_important.stderr | ne ""
    - ne .hostname .init_kubernetes_node

- include_tasks: deploy_haproxy.yaml
  when:
    - .kubernetes.haproxy.enabled
    - .groups.kube_worker | default list | has .inventory_name

- name: Add custom label to cluster
  command: |
    {{- range $k, $v := .kubernetes.custom_label }}
    /usr/local/bin/kubectl label --overwrite node {{ $.hostname }} {{ $k }}={{ $v }}
    {{- end }}
  when: .kubernetes.custom_label | len | lt 0
