How to install Kubernetes with Terraform: local kind, kubeadm on VMs, and managed clusters
The three ways to create a Kubernetes cluster with Terraform: a local kind cluster with the tehcyx/kind provider (tested with plan), VMs whose cloud-init runs kubeadm from pkgs.k8s.io, and managed clusters such as EKS, AKS, and GKE.
Kubernetes$ terraform plan▍“Installing Kubernetes with Terraform” can mean three very different things: spinning up a throwaway cluster on your machine, building your own cluster on VMs with kubeadm, or asking a cloud for a managed cluster. Terraform shows up in all three, but the job it does changes a lot. This guide covers each approach, with a complete, validated example of the local path and a realistic walkthrough of the kubeadm path. The examples use Kubernetes 1.37, the latest stable version at the time of writing.
Three paths, one tool
| Approach | What Terraform creates | Who runs the control plane | Good for |
|---|---|---|---|
| Local (kind) | Docker containers acting as nodes | You, on your machine | Testing, CI, learning |
| Self-managed (kubeadm) | VMs, networking, and the user_data that runs kubeadm |
You, including upgrades and etcd | Labs, on-premises, full control |
| Managed (EKS, AKS, GKE) | Cloud API resources | The provider | Production in the cloud |
The rule of thumb: for production in the cloud, use a managed service. kubeadm is still the best way to understand what sits underneath, and kind is unbeatable for getting a real cluster in seconds. If you are still choosing between local tools, see the comparison in lightweight local Kubernetes.
Local cluster with the tehcyx/kind provider
The community tehcyx/kind provider (version 0.13.0 in this example) uses the same library as the kind CLI. It needs Docker, or a compatible runtime, running on the machine. The advantage over kind create cluster is that the cluster is declared in code, next to whatever goes inside it, and it goes away with the same terraform destroy.
The code
Create a directory and a main.tf with one control plane and two workers. The example also configures the hashicorp/kubernetes provider from the kind outputs, so it can create a namespace right after the cluster comes up:
terraform {
required_version = ">= 1.5"
required_providers {
kind = {
source = "tehcyx/kind"
version = "0.13.0"
}
kubernetes = {
source = "hashicorp/kubernetes"
version = "3.5.0"
}
}
}
provider "kind" {}
resource "kind_cluster" "dev" {
name = "dev"
node_image = "kindest/node:v1.37.0"
wait_for_ready = true
kubeconfig_path = pathexpand("~/.kube/kind-dev")
kind_config {
kind = "Cluster"
api_version = "kind.x-k8s.io/v1alpha4"
node {
role = "control-plane"
}
node {
role = "worker"
}
node {
role = "worker"
}
}
}
provider "kubernetes" {
host = kind_cluster.dev.endpoint
client_certificate = kind_cluster.dev.client_certificate
client_key = kind_cluster.dev.client_key
cluster_ca_certificate = kind_cluster.dev.cluster_ca_certificate
}
resource "kubernetes_namespace_v1" "apps" {
metadata {
name = "apps"
}
}
output "endpoint" {
value = kind_cluster.dev.endpoint
}
output "kubeconfig_path" {
value = kind_cluster.dev.kubeconfig_path
}
output "kubeconfig" {
value = kind_cluster.dev.kubeconfig
sensitive = true
}
A few details matter. node_image pins the Kubernetes version; without it, you get the provider version’s default image. wait_for_ready = true makes apply wait until the nodes are ready. kubeconfig_path writes a separate file and leaves your ~/.kube/config alone. The kubeconfig output is marked sensitive because it contains the admin client’s private key.
Configuring a provider from a resource’s attributes in the same project works for a lab, but it is fragile: if the cluster has to be recreated, the kubernetes provider has no endpoint during plan. In serious projects, keep the cluster and what runs inside it in separate states.
init, validate, fmt, and plan
We tested this file with terraform init, validate, fmt -check, and plan. Apply was not run in this test:
terraform init
terraform validate
terraform fmt -check
terraform plan
Excerpt of the plan output:
# kind_cluster.dev will be created
+ resource "kind_cluster" "dev" {
+ endpoint = (known after apply)
+ kubeconfig_path = "/Users/you/.kube/kind-dev"
+ name = "dev"
+ node_image = "kindest/node:v1.37.0"
+ wait_for_ready = true
...
# kubernetes_namespace_v1.apps will be created
Plan: 2 to add, 0 to change, 0 to destroy.
Using the kubeconfig
After a terraform apply, point kubectl at the generated file. The context name follows the kind convention (kind-<name>):
export KUBECONFIG="$(terraform output -raw kubeconfig_path)"
kubectl get nodes -o wide
kubectl get ns apps
# or extract the content (careful: it holds admin credentials)
terraform output -raw kubeconfig > /tmp/kind-dev.yaml
# to tear everything down
terraform destroy
The lab cluster used on this blog runs exactly this topology (1 control plane and 2 workers with kindest/node:v1.37.0), created with the kind CLI v0.33.0.
Self-managed: VMs with kubeadm via cloud-init
Here Terraform creates the infrastructure (VMs, networking, security groups) and hands each machine a user_data script, which cloud-init runs on first boot. That script prepares the operating system, installs the Kubernetes packages, and runs kubeadm init on the control plane or kubeadm join on the workers. There is no official module for this; it is a common pattern, and the code below is illustrative.
What the user_data has to do
- Turn off swap and load the
overlayandbr_netfiltermodules, withnet.ipv4.ip_forward = 1. - Install a container runtime. Version 1.35 was the last to support containerd 1.x, so for 1.37 use containerd 2.x, with the
systemdcgroup driver. Also use a distro with cgroup v2, because since 1.35 the kubelet won’t start on cgroup v1 by default. - Add the pkgs.k8s.io repository. The old
apt.kubernetes.ioandyum.kubernetes.iorepos are deprecated. There is one repository per minor version, so the URL containsv1.37. - Install and pin
kubelet,kubeadm, andkubectlwithapt-mark hold, so anapt upgradecan’t trigger an accidental minor upgrade. - Run
kubeadm init(control plane) orkubeadm join(workers). - Install a CNI, such as Cilium or Calico. Without one, the nodes stay
NotReady. See Kubernetes networking.
The common script
This is the part every node runs. The pkgs.k8s.io commands follow the official documentation for 1.37:
#!/bin/bash
set -euxo pipefail
# 1. Prerequisites: swap, kernel modules, and IP forwarding
swapoff -a
sed -i '/ swap / s/^/#/' /etc/fstab
printf 'overlay\nbr_netfilter\n' > /etc/modules-load.d/k8s.conf
modprobe overlay
modprobe br_netfilter
printf 'net.ipv4.ip_forward = 1\n' > /etc/sysctl.d/k8s.conf
sysctl --system
# 2. containerd with the systemd cgroup driver
# (check that your distro's package ships containerd 2.x)
apt-get update
apt-get install -y containerd apt-transport-https ca-certificates curl gpg
mkdir -p /etc/containerd
containerd config default > /etc/containerd/config.toml
sed -i 's/SystemdCgroup = false/SystemdCgroup = true/' /etc/containerd/config.toml
systemctl restart containerd
# 3. kubeadm, kubelet, and kubectl from pkgs.k8s.io (one repository per minor)
mkdir -p -m 755 /etc/apt/keyrings
curl -fsSL https://pkgs.k8s.io/core:/stable:/v1.37/deb/Release.key \
| gpg --dearmor -o /etc/apt/keyrings/kubernetes-apt-keyring.gpg
echo 'deb [signed-by=/etc/apt/keyrings/kubernetes-apt-keyring.gpg] https://pkgs.k8s.io/core:/stable:/v1.37/deb/ /' \
> /etc/apt/sources.list.d/kubernetes.list
apt-get update
apt-get install -y kubelet kubeadm kubectl
apt-mark hold kubelet kubeadm kubectl
systemctl enable --now kubelet
init on the control plane, join on the workers
The challenge is getting the workers to join without manual steps. A simple option is to have Terraform generate the bootstrap token (format [a-z0-9]{6}.[a-z0-9]{16}, with the random provider) and inject it into both scripts with templatefile:
# control-plane.sh (after the common script)
kubeadm init \
--kubernetes-version "v1.37.2" \
--pod-network-cidr "10.244.0.0/16" \
--token "${join_token}" \
--token-ttl 2h
mkdir -p /root/.kube
cp /etc/kubernetes/admin.conf /root/.kube/config
# worker.sh (after the common script)
kubeadm join "${control_plane_ip}:6443" \
--token "${join_token}" \
--discovery-token-unsafe-skip-ca-verification
In Terraform, each aws_instance gets user_data = join("\n", [file("scripts/common.sh"), templatefile("scripts/worker.sh", { ... })]). We validated this skeleton with terraform validate (AWS provider 6.74.0) and the scripts with bash -n, and checked the kubeadm v1.37 flags with --help. It was not applied to an AWS account.
Limitations you need to know
--discovery-token-unsafe-skip-ca-verificationis for labs only. In production, use--discovery-token-ca-cert-hash sha256:...to pin the cluster CA.- Workers may boot before the control plane is ready. Wrap the
joinin a retry loop. - Open at least port 6443 (API) and 10250 (kubelet) between nodes in the security group, plus the ports your CNI needs.
- A single control plane has no high availability. With several, you need
--control-plane-endpointpointing at a load balancer, plus--upload-certs. - From here on, upgrades, certificate rotation, and etcd backups are your job. See how to upgrade a cluster.
Managed: EKS, AKS, and GKE
With managed clusters, Terraform only describes what you want and the provider’s API does the rest: there is no kubeadm and no etcd to look after. The main building blocks are:
- AWS: the
terraform-aws-modules/eks/awsmodule (21.30.2), which sets up the cluster, node groups, add-ons, and access entries. - Azure: the
azurerm_kubernetes_clusterresource. - Google Cloud: the
google_container_clusterresource, plusgoogle_container_node_pool.
The complete EKS walkthrough, with VPC, node group, add-ons, access entries, and Auto Mode, is in how to install EKS with Terraform.
Best practices for clusters in Terraform
- Pin versions of providers, modules, and the Kubernetes image or version. A
terraform init -upgrademust never change the cluster behind your back. - Use remote state with locking (S3, GCS, Azure Storage, or HCP Terraform). The state contains cluster credentials.
- Split layers: one state for the network and the cluster, another for add-ons and applications. GitOps with Argo CD is usually a better fit than Terraform for what runs inside the cluster.
- Run
validate,fmt -check, andplanin CI before any apply. If you are torn between the tools, read Terraform or OpenTofu.
Checklist
- Approach chosen to fit the use case: kind for testing, kubeadm for full control, managed for production
- Provider, module, and Kubernetes versions pinned in code
-
terraform init,validate,fmt -check, andplanrunning in CI - pkgs.k8s.io repository for the right minor, with packages under
apt-mark hold - containerd 2.x with the
systemdcgroup driver, and a CNI installed right afterkubeadm init - Production joins pin the CA hash and never skip verification
- Remote state with locking, treated as sensitive data
Terraform doesn’t install Kubernetes by itself: it declares where the cluster will live. Pick the path and let each tool handle its own part.