Skip to content

A Complete Guide to Setup a Kubernetes (K8s) Cluster Using Ansible

Steps
6
Covers
Ansible, Kubernetes
On this page 6 steps

Kubernetes is great for managing containers, making it easy for developers to deploy and scale applications. For example, you can use Kubernetes to run a website that can handle lots of traffic, manage a big data processing system, or deploy microservices. But setting up a Kubernetes cluster can be tricky, with many steps and settings. This is where Ansible helps. Ansible is a tool that automates the setup process, making it much easier to create a Kubernetes cluster.

Kubernetes Cluster Automation with Ansible
Kubernetes Cluster Automation with Ansible

In this guide, we’ll show you how to build a Kubernetes cluster with kubeadm, containerd and Calico, using three Ansible playbooks. All cluster nodes are assumed to run Ubuntu 26.04 LTS or 24.04 LTS. The playbooks install Kubernetes v1.37 from the official pkgs.k8s.io repository.

Prerequisites

Before we start the setup process, make sure you have the following:

  • Ansible: Install Ansible on your control machine. This is where you’ll run the Ansible playbooks. The control machine can be your local computer or a server.
  • Target Nodes: These are the machines where Kubernetes will be installed. You need at least two nodes: one master (control plane) node and one worker node. Each node needs at least 2 CPUs and 2 GB of RAM, a unique hostname and a unique MAC address.
  • SSH Access: Ansible uses SSH to communicate with the target nodes. Set up key-based SSH access from your control machine to all target nodes, with a user that can run sudo.

Step 1 of 6Install Ansible

First, set up Ansible on your control machine. The installation process depends on your operating system. For Ubuntu and other Debian-based systems, use these commands:

sudo apt update
sudo apt install ansible

Step 2 of 6Create the Inventory File

After installing Ansible, configure the inventory file. Create a file named hosts.ini in your working directory. This file lists all target nodes with their IP addresses, organized into the masters and workers groups. Change the IP addresses and the SSH user (ansible_user) to match your servers:


[masters]
master ansible_host=192.168.1.100

[workers]
worker1 ansible_host=192.168.1.101
worker2 ansible_host=192.168.1.102

[all:vars]
ansible_user=ubuntu
ansible_python_interpreter=/usr/bin/python3

Check that Ansible can reach every node:

ansible all -i hosts.ini -m ping

Each node should answer with "ping": "pong".

Step 3 of 6Create the Node Setup Playbook

This playbook prepares every node (master and workers) for Kubernetes. It includes tasks for:

  • Disabling the UFW firewall (fine for a lab; open the required ports instead in production)
  • Turning off swap
  • Loading the overlay and br_netfilter kernel modules and setting the network sysctl values
  • Installing the containerd runtime from Docker’s repository and switching it to the systemd cgroup driver
  • Adding the official Kubernetes repository (pkgs.k8s.io)
  • Installing kubelet, kubeadm and kubectl, and holding them at their current version

Note: Older versions of this guide used the apt.kubernetes.io (kubernetes-xenial) repository. That repository was shut down in 2024, so playbooks that still use it fail with a 404 error. Use pkgs.k8s.io as shown below. Docker Engine itself isn’t needed: Kubernetes talks to containerd directly.

Create a setup-playbook.yml file and add the following content:


- name: Prepare all nodes for Kubernetes
  hosts: all
  become: true
  vars:
    k8s_version: "v1.37"
    deb_arch: "{{ 'arm64' if ansible_architecture == 'aarch64' else 'amd64' }}"
  tasks:

    - name: Disable UFW firewall (lab setups only)
      ansible.builtin.service:
        name: ufw
        state: stopped
        enabled: false

    - name: Turn off swap
      ansible.builtin.command: swapoff -a
      when: ansible_swaptotal_mb > 0

    - name: Comment out swap entries in /etc/fstab
      ansible.builtin.replace:
        path: /etc/fstab
        regexp: '^([^#].*\sswap\s.*)$'
        replace: '# \1'

    - name: Load kernel modules at boot
      ansible.builtin.copy:
        dest: /etc/modules-load.d/k8s.conf
        content: |
          overlay
          br_netfilter

    - name: Load kernel modules now
      ansible.builtin.command: "modprobe {{ item }}"
      loop:
        - overlay
        - br_netfilter
      changed_when: false

    - name: Set the network sysctl values Kubernetes needs
      ansible.builtin.copy:
        dest: /etc/sysctl.d/k8s.conf
        content: |
          net.bridge.bridge-nf-call-iptables  = 1
          net.bridge.bridge-nf-call-ip6tables = 1
          net.ipv4.ip_forward                 = 1

    - name: Apply sysctl values
      ansible.builtin.command: sysctl --system
      changed_when: false

    - name: Install required packages
      ansible.builtin.apt:
        name:
          - ca-certificates
          - curl
        state: present
        update_cache: true

    - name: Create the APT keyrings directory
      ansible.builtin.file:
        path: /etc/apt/keyrings
        state: directory
        mode: "0755"

    - name: Add Docker GPG key
      ansible.builtin.get_url:
        url: https://download.docker.com/linux/ubuntu/gpg
        dest: /etc/apt/keyrings/docker.asc
        mode: "0644"

    - name: Add Docker repository (for containerd)
      ansible.builtin.apt_repository:
        repo: "deb [arch={{ deb_arch }} signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu {{ ansible_distribution_release }} stable"
        filename: docker
        state: present

    - name: Install containerd
      ansible.builtin.apt:
        name: containerd.io
        state: present
        update_cache: true

    - name: Generate the default containerd config
      ansible.builtin.shell: containerd config default > /etc/containerd/config.toml

    - name: Use the systemd cgroup driver in containerd
      ansible.builtin.replace:
        path: /etc/containerd/config.toml
        regexp: 'SystemdCgroup = false'
        replace: 'SystemdCgroup = true'

    - name: Restart and enable containerd
      ansible.builtin.service:
        name: containerd
        state: restarted
        enabled: true

    - name: Add Kubernetes GPG key
      ansible.builtin.get_url:
        url: "https://pkgs.k8s.io/core:/stable:/{{ k8s_version }}/deb/Release.key"
        dest: /etc/apt/keyrings/kubernetes-apt-keyring.asc
        mode: "0644"

    - name: Add Kubernetes repository
      ansible.builtin.apt_repository:
        repo: "deb [signed-by=/etc/apt/keyrings/kubernetes-apt-keyring.asc] https://pkgs.k8s.io/core:/stable:/{{ k8s_version }}/deb/ /"
        filename: kubernetes
        state: present

    - name: Install kubelet, kubeadm and kubectl
      ansible.builtin.apt:
        name:
          - kubelet
          - kubeadm
          - kubectl
        state: present
        update_cache: true

    - name: Hold Kubernetes packages at their current version
      ansible.builtin.dpkg_selections:
        name: "{{ item }}"
        selection: hold
      loop:
        - kubelet
        - kubeadm
        - kubectl

    - name: Enable kubelet
      ansible.builtin.service:
        name: kubelet
        enabled: true

Execute the playbook by running:

ansible-playbook -i hosts.ini setup-playbook.yml

If your SSH user needs a password for sudo, add the -K option to this and the following ansible-playbook commands.

Step 4 of 6Create the Master Node Playbook

This playbook configures the master (control plane) node. It initializes the cluster with kubeadm init, using the master’s IP address from the inventory as the API server address, and copies the kubeconfig file to your user’s ~/.kube/config so you can manage the cluster with kubectl. It then installs the Calico network plugin, which handles pod networking so pods can talk to each other across nodes.

Create a file named master-playbook.yml and add the following content:


- name: Configure the master node
  hosts: masters
  become: true
  vars:
    pod_network_cidr: "10.244.0.0/16"
    calico_version: "v3.33.0"
  tasks:

    - name: Initialize the Kubernetes cluster
      ansible.builtin.command: >
        kubeadm init
        --pod-network-cidr={{ pod_network_cidr }}
        --apiserver-advertise-address={{ ansible_host }}
      args:
        creates: /etc/kubernetes/admin.conf

    - name: Create the .kube directory for {{ ansible_user }}
      ansible.builtin.file:
        path: "~{{ ansible_user }}/.kube"
        state: directory
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        mode: "0755"

    - name: Copy the kubeconfig file to {{ ansible_user }}
      ansible.builtin.copy:
        src: /etc/kubernetes/admin.conf
        dest: "~{{ ansible_user }}/.kube/config"
        remote_src: true
        owner: "{{ ansible_user }}"
        group: "{{ ansible_user }}"
        mode: "0600"

    - name: Install the Calico pod network
      ansible.builtin.command: >
        kubectl apply --server-side
        -f https://raw.githubusercontent.com/projectcalico/calico/{{ calico_version }}/manifests/calico.yaml
      environment:
        KUBECONFIG: /etc/kubernetes/admin.conf

The pod network CIDR (10.244.0.0/16) must not overlap with your node network. Calico reads it from the kubeadm configuration automatically, so you don’t need to edit the Calico manifest.

Execute the playbook with this command:

ansible-playbook -i hosts.ini master-playbook.yml

Step 5 of 6Create the Worker Nodes Playbook

This playbook adds the worker nodes to the cluster. The first play runs on the master node and creates a join command with kubeadm token create --print-join-command. The second play runs on the worker nodes and uses that command to join them to the cluster. Nodes that have already joined are skipped, so you can run the playbook again after adding new workers to the inventory.

Create a file named worker-playbook.yml and add the following content:


- name: Generate the join command on the master node
  hosts: masters
  become: true
  gather_facts: false
  tasks:
    - name: Get the join command
      ansible.builtin.command: kubeadm token create --print-join-command
      register: join_command
      changed_when: false

- name: Join the worker nodes to the cluster
  hosts: workers
  become: true
  gather_facts: false
  tasks:
    - name: Join the cluster
      ansible.builtin.command: "{{ hostvars[groups['masters'][0]].join_command.stdout }}"
      args:
        creates: /etc/kubernetes/kubelet.conf

Execute the playbook with this command:

ansible-playbook -i hosts.ini worker-playbook.yml

Step 6 of 6Verify the Cluster

Once the playbooks have run, check that the Kubernetes cluster is set up correctly. Log in to the master node as the user from the inventory and run:

kubectl get nodes

All nodes should be listed. They change to the Ready status after the Calico pods start, which can take a minute or two. To check the system pods, including Calico and CoreDNS, run:

kubectl get pods -n kube-system

All pods should show the Running status.

Conclusion

By following these steps, you have successfully set up a Kubernetes cluster using Ansible. This method provides a scalable and repeatable process, making it easier to manage and automate the deployment of Kubernetes clusters. As you get more comfortable with Ansible and Kubernetes, you can customize your playbooks to fit your needs, like adding more worker nodes or setting up advanced features.

Rahul

Rahul Kumar is the founder and chief editor of TecAdmin.net. A Red Hat Certified Engineer (RHCE), he has worked in IT since 2009, with hands-on experience in Linux system administration, DevOps, web hosting, cloud platforms and automation. He started TecAdmin in 2013 to share practical, step-by-step guides, and leads its editorial work with one aim: making technical learning clear and useful for sysadmins, developers and beginners alike.

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *


Back to top