---
- name: Set external kube-apiserver endpoint
  set_fact:
    external_apiserver_address: >-
      {%- if loadbalancer_apiserver is defined and loadbalancer_apiserver.address is defined -%}
      {{ loadbalancer_apiserver.address }}
      {%- else -%}
      {{ kube_apiserver_access_address }}
      {%- endif -%}
    external_apiserver_port: >-
      {%- if loadbalancer_apiserver is defined and loadbalancer_apiserver.address is defined and loadbalancer_apiserver.port is defined -%}
      {{ loadbalancer_apiserver.port|default(kube_apiserver_port) }}
      {%- else -%}
      {{ kube_apiserver_port }}
      {%- endif -%}
  tags:
    - facts

- name: Create kube config dir
  file:
    path: "/root/.kube"
    mode: "0700"
    state: directory

- name: Copy admin kubeconfig to root user home
  copy:
    src: "{{ kube_config_dir }}/admin.conf"
    dest: "/root/.kube/config"
    remote_src: yes
    mode: "0600"
    backup: yes

- name: Create kube artifacts dir
  file:
    path: "{{ artifacts_dir }}"
    mode: "0750"
    state: directory
  delegate_to: localhost
  become: no
  run_once: yes
  when: kubeconfig_localhost|default(false)

- name: Generate admin kubeconfig with external api endpoint
  shell: >-
    {{ bin_dir }}/kubeadm alpha
    {% if kubeadm_version is version('v1.13.0', '<') %}
    phase
    {% endif %}
    kubeconfig user
    --client-name kubernetes-admin
    --org system:masters
    --cert-dir {{ kube_cert_dir }}
    --apiserver-advertise-address {{ external_apiserver_address }}
    --apiserver-bind-port {{ external_apiserver_port }}
  run_once: yes
  register: admin_kubeconfig

- name: Write admin kubeconfig on ansible host
  copy:
    content: "{{ admin_kubeconfig.stdout }}"
    dest: "{{ artifacts_dir }}/admin.conf"
    mode: 0640
  delegate_to: localhost
  become: no
  run_once: yes
  when: kubeconfig_localhost|default(false)

- name: Copy kubectl binary to ansible host
  fetch:
    src: "{{ bin_dir }}/kubectl"
    dest: "{{ artifacts_dir }}/kubectl"
    flat: yes
    validate_checksum: no
  become: no
  run_once: yes
  when: kubectl_localhost|default(false)

- name: create helper script kubectl.sh on ansible host
  copy:
    content: |
      #!/bin/bash
      kubectl --kubeconfig=${BASH_SOURCE%/*}/admin.conf $@
    dest: "{{ artifacts_dir }}/kubectl.sh"
    mode: 0755
  become: no
  run_once: yes
  delegate_to: localhost
  when: kubectl_localhost|default(false) and kubeconfig_localhost|default(false)
