---
- name: Generate kubeadm join config
  template:
    src: |
      {{- if .kube_version | semverCompare ">=v1.24.0" }}
      kubeadm/kubeadm-join.v1beta3
      {{- else }}
      kubeadm/kubeadm-join.v1beta2
      {{- end }}
    dest: /etc/kubernetes/kubeadm-config.yaml

- name: Sync audit policy file to remote
  copy:
    src: audit
    dest: /etc/kubernetes/audit/
  when: .kubernetes.audit

- name: Join kubernetes cluster
  block:
    - name: Join kubernetes by kubeadm
      command: |
        /usr/local/bin/kubeadm join --config=/etc/kubernetes/kubeadm-config.yaml --ignore-preflight-errors=FileExisting-crictl,ImagePull
  rescue:
    - name: Reset kubeadm if join failed
      command: kubeadm reset -f {{ if and .cri.cri_socket (ne .cri.cri_socket "") }}--cri-socket {{ .cri.cri_socket }}{{ end }}

- name: Sync kubeconfig to remote
  copy:
    src: |
      {{ .work_dir }}/kubekey/kubeconfig
    dest: /root/.kube/config

- name: Set to worker node
  when: .groups.kube_worker | default list | has .inventory_name
  block:
    - name: Remote master taint
      ignore_errors: true
      command: |
        /usr/local/bin/kubectl taint nodes {{ .hostname }} node-role.kubernetes.io/master=:NoSchedule-
        /usr/local/bin/kubectl taint nodes {{ .hostname }} node-role.kubernetes.io/control-plane=:NoSchedule-
    - name: Add work label
      command: |
        /usr/local/bin/kubectl label --overwrite node {{ .hostname }} node-role.kubernetes.io/worker=
