---
- name: Add docker apt key
  apt_key:
    url: https://download.docker.com/linux/{{ ansible_distribution | lower }}/gpg

- name: Add docker apt repository
  apt_repository:
    repo: deb [arch=amd64] https://download.docker.com/linux/{{ ansible_distribution | lower }} {{ ansible_distribution_release }} stable
    filename: docker
  register: containerd_apt_repo_task

- name: apt list --upgradable
  command: apt list --upgradable
  when: containerd_apt_repo_task.changed  

- name: apt update
  apt:
    update_cache: yes
  when: containerd_apt_repo_task.changed

- name: Create containerd configuration directory
  file:
    path: /etc/containerd
    state: directory

- name: Configure containerd
  template:
    src: config.toml.j2
    dest: /etc/containerd/config.toml
  notify:
    - Restart containerd service

- name: Install required packages
  apt:
    name:
      - containerd.io
  notify:
    - Reload systemd configuration
    - Restart containerd service

- meta: flush_handlers

- name: Enable containerd service
  service:
    name: containerd
    enabled: True
    state: started
   
- 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

