---
- name: Install kubernetes
  block:
    - name: 'Add kubernetes repo key'
      apt_key:
        url: https://packages.cloud.google.com/apt/doc/apt-key.gpg
        state: present
      become: true
    - name: Add kubernetes repository
      apt_repository:
        repo: deb http://apt.kubernetes.io kubernetes-xenial main
        state: present
        filename: 'kubernetes'
      become: true
    - name: Install kubernetes components
      apt: 
        name: ['kubelet={{kubernetes_version}}-*', 'kubeadm={{kubernetes_version}}-*', 'kubectl={{kubernetes_version}}-*']
        state: present
        update_cache: yes
        #force: yes
        #dpkg_options: force-downgrade

- name: Hold kubernetes packages
  dpkg_selections:
    name: "{{item}}"
    selection: hold
  with_items:
    - kubelet
    - kubectl
    - kubeadm

- name: Enable kubelet service
  systemd:
    name: kubelet
    enabled: true
    masked: false

- name: Check if Kubernetes has already been initialized.
  stat:
    path: /etc/kubernetes/admin.conf
  register: kubernetes_init_stat


          
# Set up master.
- include_tasks: k8s-master.yml
  when: kubernetes_role == 'master'

# Set up nodes.
- name: Get the kubeadm join command from the Kubernetes master.
  command: kubeadm token create --print-join-command
  changed_when: false
  when: kubernetes_role == 'master'
  register: kubernetes_join_command_result

- name: Set the kubeadm join command globally.
  set_fact:
    kubernetes_join_command: >
      {{ kubernetes_join_command_result.stdout }}
      {{ kubernetes_join_command_extra_opts }}
  when: kubernetes_join_command_result.stdout is defined
  delegate_to: "{{ item }}"
  delegate_facts: true
  with_items: "{{ groups['all'] }}"

- include_tasks: k8s-node.yml
  when: kubernetes_role == 'node'
     
