---
- hosts: all 
  become: true
  tasks:
    - include_vars: vars/vars.yaml # Contains tasks variables for installer
    - include_tasks: tasks/bootstrap_ubuntu.yaml # Contains tasks bootstrap components for ubuntu systems 
      when: ansible_distribution == "Ubuntu"
    - include_tasks: tasks/bootstrap_centos.yaml # Contains tasks bootstrap components for centos systems
      when: ansible_distribution == "CentOS"
    - include_tasks: tasks/k8s.yaml # Contains tasks kubernetes component installation
    - include_tasks: tasks/binaries.yaml # Contains tasks for pulling containerd and cri-containerd components

    - name: "Create a directory for containerd config"
      file: path=/etc/containerd state=directory

    - name: "Add containerd config file"
      blockinfile:
        path: /etc/containerd/config.toml
        create: yes
        block: |
          [cgroup]
            path = "/runtime"

    - name: "Create a directory for cri-containerd config"
      file: path=/etc/cri-containerd state=directory

    - name: "Add cri-containerd config file"
      blockinfile:
        path: /etc/cri-containerd/config.toml
        create: yes
        block: |
          cgroup_path = "/runtime"

    - name: "Start Containerd"
      systemd: name=containerd daemon_reload=yes state=started enabled=yes

    - name: "Start CRI-Containerd"
      systemd: name=cri-containerd daemon_reload=yes state=started enabled=yes

    - name: "Load br_netfilter kernel module"
      modprobe:
        name: br_netfilter
        state: present

    - name: "Set bridge-nf-call-iptables" 
      sysctl:
        name: net.bridge.bridge-nf-call-iptables
        value: 1

    - name: "Set ip_forward" 
      sysctl:
        name: net.ipv4.ip_forward
        value: 1

    - name: "Check kubelet args in kubelet config"
      shell: grep "^Environment=\"KUBELET_EXTRA_ARGS=" /etc/systemd/system/kubelet.service.d/10-kubeadm.conf || true
      register: check_args

    - name: "Add runtime args in kubelet conf"
      lineinfile:
        dest: "/etc/systemd/system/kubelet.service.d/10-kubeadm.conf"
        line: "Environment=\"KUBELET_EXTRA_ARGS= --runtime-cgroups=/runtime --container-runtime=remote --runtime-request-timeout=15m --container-runtime-endpoint=/var/run/cri-containerd.sock\""
        insertafter: '\[Service\]'
      when: check_args.stdout == ""
    
    - name: "Start Kubelet"
      systemd: name=kubelet daemon_reload=yes state=started enabled=yes
    
    # TODO This needs to be removed once we have consistent concurrent pull results
    - name: "Pre-pull pause container image"
      shell: |
        /usr/local/bin/ctr pull gcr.io/google_containers/pause:3.0
        /usr/local/bin/crictl --runtime-endpoint /var/run/cri-containerd.sock \
        pull gcr.io/google_containers/pause:3.0
