Skip to content
All writing

Automating Kubernetes with infrastructure as code: Ansible and Terraform

Infrastructure-as-code practices for deploying and managing Kubernetes clusters in a repeatable way.

Published
Reading time
2 minutes
Topics
Kubernetes, IaC, DevOps

Running Kubernetes clusters by hand does not scale. Infrastructure as code with Terraform and Ansible turns a cluster into something you can rebuild, review and version like any other code.

The workflow

Each tool does what it is best at:

  • Terraform provisions the resources: virtual machines, networks, storage
  • Ansible configures them and installs Kubernetes on top

Provisioning with Terraform

Terraform’s declarative syntax describes the state you want. A set of control-plane nodes on vSphere:

resource "vsphere_virtual_machine" "control_plane" {
  count            = 3
  name             = "k8s-cp-${count.index + 1}"
  resource_pool_id = data.vsphere_compute_cluster.lab.resource_pool_id
  datastore_id     = data.vsphere_datastore.ds.id
  num_cpus         = 2
  memory           = 4096
  guest_id         = data.vsphere_virtual_machine.ubuntu.guest_id

  network_interface {
    network_id = data.vsphere_network.k8s.id
  }

  disk {
    label = "disk0"
    size  = 40
  }

  clone {
    template_uuid = data.vsphere_virtual_machine.ubuntu.id
  }
}

Configuration with Ansible

Once the machines exist, Ansible installs and configures Kubernetes:

  • the container runtime (containerd)
  • cluster bootstrap with kubeadm — or the whole job handed to Kubespray
  • the CNI plugin (Calico or Flannel)
- name: Prepare Kubernetes nodes
  hosts: k8s
  become: true
  tasks:
    - name: Load kernel modules
      community.general.modprobe:
        name: "{{ item }}"
        persistent: present
      loop: [overlay, br_netfilter]

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

    - name: Initialise the control plane
      ansible.builtin.command: kubeadm init --pod-network-cidr=10.244.0.0/16
      args:
        creates: /etc/kubernetes/admin.conf
      when: inventory_hostname == groups['control_plane'][0]

GitOps for applications

Combine infrastructure as code with a GitOps controller such as Flux or Argo CD for continuous delivery. The cluster then converges on whatever is in Git, and drift becomes visible instead of silent.

Best practices

  • Keep Terraform state in a remote backend (S3, Azure Blob Storage) with locking.
  • Use Ansible Vault — or an external secrets manager — for credentials.
  • Validate infrastructure code in CI: terraform validate, ansible-lint, a plan on every pull request.
Esc
↑ ↓ moveEnter open> shell