

---

- name: Create k0s initial controller service with install command
  register: install_initial_controller_cmd
  command: k0s install controller --config {{ k0s_config_dir }}/k0s.yaml {{ extra_args | default(omit) }}
  changed_when: install_initial_controller_cmd | length > 0

- name: Setup custom environment variables for systemd unit
  include_role:
    name: env_setup

- name: Enable and check k0s service
  systemd:
    name: k0scontroller
    daemon_reload: yes
    state: restarted
    enabled: yes

- name: Wait for k8s apiserver
  wait_for:
    host: localhost
    port: 6443
    delay: 15
    timeout: 180

- name: Create worker join token
  register: worker_join_token
  command: k0s token create --role worker  --config {{ k0s_config_dir }}/k0s.yaml
  changed_when: worker_join_token | length > 0

- name: Store worker join token
  set_fact:
    join_token_worker: "{{ worker_join_token.stdout }}"
    cacheable: yes

- name: Add k0s worker token to dummy host
  add_host:
    name: "worker_token_holder"
    token: "{{ worker_join_token.stdout }}"

- name: Print worker token
  debug:
    msg: "k0s worker join token is: {{ worker_join_token.stdout }}"

- name: Create controller join token
  register: controller_join_token
  command: k0s token create --role controller --config {{ k0s_config_dir }}/k0s.yaml
  changed_when: controller_join_token | length > 0

- name: Store controller join token
  set_fact:
    join_token_controller: "{{ controller_join_token.stdout }}"
    cacheable: yes

- name: Add k0s controller token to dummy host
  add_host:
    name: "controller_token_holder"
    token: "{{ controller_join_token.stdout }}"

- name: Print controller token
  debug:
    msg: "k0s controller join token is: {{ controller_join_token.stdout }}"

- name: Copy config file to user home directory
  copy:
    src: "{{ k0s_data_dir }}/pki/admin.conf"
    dest: ~{{ ansible_user }}/k0s-kubeconfig.yml
    remote_src: yes
    owner: "{{ ansible_user }}"
    mode: 0644

- name: Set controller IP in kubeconfig
  replace:
    path: ~{{ ansible_user }}/k0s-kubeconfig.yml
    regexp: 'localhost'
    replace: "{{ ansible_host }}"

- name: Copy kubeconfig
  fetch:
    src: "~{{ ansible_user }}/k0s-kubeconfig.yml"
    dest: "{{ artifacts_dir }}/k0s-kubeconfig.yml"
    flat: yes
    validate_checksum: no
  become: no

- name: "print kubeconfig command"
  debug:
    msg: "To use Cluster: export KUBECONFIG={{ artifacts_dir }}/k0s-kubeconfig.yml"
