---
- name: Kubectl | Fail if playbook is executed on K8s master
  fail:
    msg: "The kubectl_client.yml playbook is not meant to run on K8s master"
  when: master

- name: Kubectl | Generate K8s client certs for kubectl
  import_tasks: ./k8s_client_certs.yml

- name: Kubectl | Include global vars
  include_vars: "{{ ansible_tmp_dir }}/generated_global_vars.yml"

- name: Kubectl | Fail if MASTER_IP global var is not set
  fail:
    msg: "The global config MASTER_IP is not set"
  when: MASTER_IP is not defined

- name: Kubectl | Get the Kubectl file stat
  stat:
    path: /usr/bin/kubectl
  register: kubectl_bin

- name: Kubectl | Setup kubectl binary
  block:
    - name: Kubectl | Get the tmp Kubectl file stat
      stat:
        path: "{{ ansible_tmp_dir }}/kubectl"
      register: tmp_kubectl_bin

    - name: Kubectl | Copy the binary from the Ansible machine
      copy:
        src: "{{ ansible_tmp_dir }}/kubectl"
        dest: /usr/bin/kubectl
        owner: root
        group: root
        mode: "u=rwx,g=rx,o=rx"
  when: not kubectl_bin.stat.exists

- name: Kubectl | Setting kubectl context
  shell: |
    set -o errexit
    kubectl config set-cluster default-cluster --server=https://{{ MASTER_IP }} --certificate-authority=/etc/kubernetes/tls/ca.pem
    kubectl config set-credentials default-admin --certificate-authority=/etc/kubernetes/tls/ca.pem --client-key=/etc/kubernetes/tls/node-key.pem --client-certificate=/etc/kubernetes/tls/node.pem
    kubectl config set-context local --cluster=default-cluster --user=default-admin
    kubectl config use-context local
