Terraform on Your Laptop (Part 4)

Neil Haddley โ€ข November 29, 2026

Terraform and Kubernetes together: Terraform created a Kubernetes cluster and the objects in it, then I deleted pods, deleted a Deployment, scaled, rolled out new code and broke a copy to see who fixed what.

DevOpsDockerKubernetesTerraformterraformkuberneteskinddockerinfrastructure-as-code

People often ask what the difference is between Terraform and Kubernetes. The usual answer is that you can use both, and that answer is easy to say and hard to picture. So in this post I use both on the same web site and database from Part 3, and I watch which tool fixes what.

Terraform creates a Kubernetes cluster and the objects inside it. Then I delete a pod, delete a whole Deployment, scale the site, roll out new code and break one copy on purpose. After each step I look at what Kubernetes did, what Terraform did, and what the web site looked like to a visitor.

I ran everything on Docker Desktop on my Mac with Terraform 1.17.2. I already have a Kubernetes post from 2021 that uses kubectl and a YAML file by hand, and three posts on Amazon EKS. This post is about how Kubernetes sits next to Terraform, not how to learn Kubernetes.

The difference in one table

TerraformKubernetes
What it isA tool that makes real infrastructure match a fileA system that runs containers and keeps them running
When it actsWhen I run plan and applyAll the time, in a loop
What it managesClusters, databases, networks, volumes, and also Kubernetes objectsPods, Deployments, Services
If something is deleted by handNotices at the next plan, and puts it back at the next applyPods: puts them back at once. Other objects: does not know they were meant to exist
KeepsA state file of what it createdThe desired state in the cluster
Terraform declares the objects when I run it. Kubernetes watches the pods all the time. The animation shows what each one does when I delete thingsScroll sideways, or tap the diagram to open it full size

Terraform declares the objects when I run it. Kubernetes watches the pods all the time. The animation shows what each one does when I delete things

A cluster that Terraform can create

Docker Desktop has its own Kubernetes, but it is a setting in the app. Terraform cannot create it, and I did not switch it on. Instead I let Terraform create a small cluster with kind, which stands for "Kubernetes in Docker". The whole cluster runs inside one Docker container, which kind calls a node. That is the same split as in the cloud: Terraform creates the cluster, as it would an AKS or EKS cluster, and then it creates the Kubernetes objects.

You can download the files: main.tf, init.sql, Program.cs, site.csproj, Dockerfile and terraform.tfvars. I started from an empty state, because in this post pods replace the web containers from Part 3.

What stays the same: the C# site, the visit counter and the T-SQL stored procedures. What changes:

  • The web site moves into the cluster as a Deployment of identical pods, with a Service in front of them.
  • The database stays in Docker, outside the cluster. SQL Server's image is built for Intel processors and the Kubernetes node on my Mac is Arm, so the cluster could not pull it. Keeping the database outside the cluster is also a common real layout. The database container joins the Docker network that kind creates, so the pods reach it by its name.
  • Two new endpoints in the C# app. /healthz answers ok, and /break makes that one copy unhealthy so that its pages and /healthz return HTTP 500. I use them in Step 6. Kubernetes uses /healthz for its health probes.

The Terraform file

The file starts with two more providers, tehcyx/kind and hashicorp/kubernetes 3.6.0, and then keeps the pieces from Part 3. These are the new parts. First, the Kubernetes provider is configured from the cluster that Terraform creates in the same file:

HCL
1provider "kubernetes" {
2  host                   = kind_cluster.demo.endpoint
3  client_certificate     = kind_cluster.demo.client_certificate
4  client_key             = kind_cluster.demo.client_key
5  cluster_ca_certificate = kind_cluster.demo.cluster_ca_certificate
6}

The cluster itself is a single node. The extra_port_mappings block publishes the node's port 30080 on my Mac's port 8080:

HCL
1resource "kind_cluster" "demo" {
2  name           = "tfdemo"
3  wait_for_ready = true
4
5  kind_config {
6    kind        = "Cluster"
7    api_version = "kind.x-k8s.io/v1alpha4"
8
9    node {
10      role = "control-plane"
11
12      extra_port_mappings {
13        container_port = 30080
14        host_port      = 8080
15      }
16    }
17  }
18}

The database container now joins the kind network, which exists once the cluster does:

HCL
1  networks_advanced {
2    name = "kind"
3  }

The pods run an image that I build locally, so Terraform builds it and loads it into the cluster node. The image tag is the first eight characters of a fingerprint of the source files, so a code change gives a new tag, and the Deployment notices:

HCL
1locals {
2  source_hash = sha1(join("", [
3    for f in sort(fileset("${path.module}/app", "*")) :
4    filesha1("${path.module}/app/${f}")
5  ]))
6  site_image = "terraform-demo-site:${substr(local.source_hash, 0, 8)}"
7}
8
9resource "terraform_data" "load_image" {
10  triggers_replace = [docker_image.site.image_id, kind_cluster.demo.id]
11
12  provisioner "local-exec" {
13    command = "docker save ${local.site_image} | docker exec -i tfdemo-control-plane ctr --namespace=k8s.io images import --all-platforms -"
14  }
15}

Then the Kubernetes objects. A namespace and a Secret that holds the connection string:

HCL
1resource "kubernetes_namespace_v1" "demo" {
2  metadata {
3    name = "demo"
4  }
5
6  depends_on = [kind_cluster.demo]
7}
8
9resource "kubernetes_secret_v1" "db" {
10  metadata {
11    name      = "db-connection"
12    namespace = kubernetes_namespace_v1.demo.metadata[0].name
13  }
14
15  data = {
16    DB_CONNECTION = "Server=terraform-demo-db;Database=ShopDemo;User Id=sa;Password=${random_password.sa.result};TrustServerCertificate=True"
17  }
18}

The Deployment is the heart of it. It declares the number of copies, how to update them, and two health probes:

HCL
1resource "kubernetes_deployment_v1" "site" {
2  metadata {
3    name      = "site"
4    namespace = kubernetes_namespace_v1.demo.metadata[0].name
5  }
6
7  spec {
8    replicas = var.replicas
9
10    selector {
11      match_labels = {
12        app = "site"
13      }
14    }
15
16    strategy {
17      type = "RollingUpdate"
18
19      rolling_update {
20        max_surge       = "1"
21        max_unavailable = "0"
22      }
23    }
24
25    template {
26      metadata {
27        labels = {
28          app = "site"
29        }
30      }
31
32      spec {
33        container {
34          name              = "site"
35          image             = local.site_image
36          image_pull_policy = "IfNotPresent"
37
38          port {
39            container_port = 8080
40          }
41
42          env {
43            name  = "SITE_TITLE"
44            value = var.site_title
45          }
46
47          env {
48            name  = "SITE_COLOR"
49            value = var.site_color
50          }
51
52          env {
53            name = "DB_CONNECTION"
54
55            value_from {
56              secret_key_ref {
57                name = kubernetes_secret_v1.db.metadata[0].name
58                key  = "DB_CONNECTION"
59              }
60            }
61          }
62
63          readiness_probe {
64            http_get {
65              path = "/healthz"
66              port = 8080
67            }
68
69            period_seconds    = 2
70            failure_threshold = 2
71          }
72
73          liveness_probe {
74            http_get {
75              path = "/healthz"
76              port = 8080
77            }
78
79            initial_delay_seconds = 5
80            period_seconds        = 5
81            failure_threshold     = 3
82          }
83        }
84      }
85    }
86  }
87
88  depends_on = [terraform_data.load_image, terraform_data.db_schema]
89}

Three things in the Deployment matter for the steps below:

  • strategy with max_unavailable = "0" means Kubernetes starts a new pod and waits until it is ready before stopping an old one.
  • The readiness probe asks /healthz every 2 seconds. After two failures, Kubernetes takes the pod out of the Service, so visitors stop reaching it.
  • The liveness probe asks /healthz every 5 seconds. After three failures, Kubernetes restarts the container.

Finally the Service, which gives one stable port in front of all of the pods:

HCL
1resource "kubernetes_service_v1" "site" {
2  metadata {
3    name      = "site"
4    namespace = kubernetes_namespace_v1.demo.metadata[0].name
5  }
6
7  spec {
8    type = "NodePort"
9
10    selector = {
11      app = "site"
12    }
13
14    port {
15      port        = 80
16      target_port = 8080
17      node_port   = 30080
18    }
19  }
20}

Step 1: create everything

PROMPT
1terraform init
2terraform plan
3terraform apply -auto-approve

The plan said Plan: 12 to add, 0 to change, 0 to destroy. The password and the Secret's data were hidden as (sensitive value), as in Part 3. The apply went in dependency order. The cluster took 26 seconds, the database container 12, and the whole run about 40:

CODE
1kind_cluster.demo: Creation complete after 26s
2kubernetes_namespace_v1.demo: Creation complete after 0s
3kubernetes_secret_v1.db: Creation complete after 0s
4kubernetes_service_v1.site: Creation complete after 0s
5terraform_data.load_image: Creation complete after 3s
6docker_container.db: Creation complete after 12s
7terraform_data.db_schema: Creation complete after 0s
8kubernetes_deployment_v1.site: Creation complete after 2s
9
10Apply complete! Resources: 12 added, 0 changed, 0 destroyed.

Then I looked at the cluster with kubectl:

CODE
1$ kubectl -n demo get pods,svc
2NAME                        READY   STATUS    RESTARTS   AGE
3pod/site-5b8cf6cccc-559pd   1/1     Running   0          5s
4pod/site-5b8cf6cccc-7vfzf   1/1     Running   0          5s
5pod/site-5b8cf6cccc-jl7n7   1/1     Running   0          5s
6
7NAME           TYPE       CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
8service/site   NodePort   10.96.199.118   <none>        80:30080/TCP   17s

I sent requests to http://localhost:8080 for six seconds. All 51 succeeded, and they were spread across all three pods. One port, three copies: that is the Service load balancing.

The site on port 8080. The "Served by container" name is now a pod name, and the visits are counted per pod

The site on port 8080. The "Served by container" name is now a pod name, and the visits are counted per pod

Docker Desktop shows only two containers. The pods are not among them, because they run inside the node:

Docker Desktop: the kind node, which publishes 8080 to its port 30080, and the SQL Server container. The three pods are inside the node container

Docker Desktop: the kind node, which publishes 8080 to its port 30080, and the SQL Server container. The three pods are inside the node container

Step 2: delete a pod

I deleted one pod by hand, with Kubernetes, not Terraform:

CODE
1$ kubectl -n demo delete pod site-5b8cf6cccc-559pd --wait=false
2
3$ kubectl -n demo get pods
4NAME                    READY   STATUS    RESTARTS   AGE
5site-5b8cf6cccc-7vfzf   1/1     Running   0          2m21s
6site-5b8cf6cccc-jl7n7   1/1     Running   0          2m21s
7site-5b8cf6cccc-qpb2k   1/1     Running   0          1s

A new pod, qpb2k, was already running one second later. While I did this, a program sent a request every tenth of a second for 12 seconds. All 105 requests succeeded. Then I asked Terraform:

PROMPT
1terraform plan
CODE
1No changes. Your infrastructure matches the configuration.

Terraform did not notice and did not need to. The Deployment still says three copies, and there are three copies. Kubernetes put the pod back without Terraform being involved.

Step 3: delete the Deployment

Now the opposite. I deleted the Deployment itself:

CODE
1$ kubectl -n demo delete deployment site
2deployment.apps "site" deleted from demo namespace
3
4$ kubectl -n demo get pods
5No resources found in demo namespace.

Eight seconds later there were still no pods, and a request to the site failed. Nothing in Kubernetes recreated it, because the Deployment was the thing that asked for the pods. Terraform knew:

PROMPT
1terraform plan
CODE
1# kubernetes_deployment_v1.site will be created
2
3Plan: 1 to add, 0 to change, 0 to destroy.
CODE
1kubernetes_deployment_v1.site: Creation complete after 4s
2Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

Of 104 requests sent during the recovery, 96 succeeded and 8 failed in the first couple of seconds, before the new pods were ready. Once the Deployment existed again, Kubernetes created the pods.

Step 4: scale with Terraform

I changed replicas in terraform.tfvars from 3 to 5:

PROMPT
1terraform plan
CODE
1# kubernetes_deployment_v1.site will be updated in-place
2  ~ spec {
3      ~ replicas = "3" -> "5"
4
5Plan: 0 to add, 1 to change, 0 to destroy.

One change in place, nothing destroyed. The apply took 2 seconds, and Kubernetes did the work:

CODE
1$ kubectl -n demo get pods
2NAME                    READY   STATUS    RESTARTS   AGE
3site-5b8cf6cccc-2xnhl   1/1     Running   0          1s
4site-5b8cf6cccc-59xdb   1/1     Running   0          1s
5site-5b8cf6cccc-drtqr   1/1     Running   0          21s
6site-5b8cf6cccc-fc8mp   1/1     Running   0          21s
7site-5b8cf6cccc-m5blf   1/1     Running   0          21s

The three old pods were not touched. In Part 2, scaling meant Terraform creating containers one by one. Here Terraform changes a number and Kubernetes carries it out. I sent requests for 8 seconds: all 69 succeeded, spread over five pods.

Step 5: roll out new code

I edited Program.cs again: the version became 4.1 and I added a card saying the shop opens from 9am to 5pm. Then, while a program sent ten requests a second, I ran terraform apply.

PROMPT
1terraform plan
CODE
1# docker_image.site must be replaced
2    ~ name = "terraform-demo-site:9e96157b" -> "terraform-demo-site:a466eb04" # forces replacement
3# kubernetes_deployment_v1.site will be updated in-place
4    ~ image = "terraform-demo-site:9e96157b" -> "terraform-demo-site:a466eb04"
5# terraform_data.load_image must be replaced
6
7Plan: 2 to add, 1 to change, 2 to destroy.

Terraform rebuilt the image, loaded it into the node, and changed one thing in the Deployment: the image tag. It did not touch the pods. Kubernetes saw the new tag and rolled the pods over. The apply finished its Deployment change in 7 seconds. Afterwards:

CODE
1$ kubectl -n demo get rs
2NAME              DESIRED   CURRENT   READY   AGE
3site-5b8cf6cccc   0         0         0       54s
4site-6b849898fc   5         5         5       8s

The old ReplicaSet was scaled down to zero and the new one to five. During the apply, the requests showed the rollover:

CODE
1requests: 349   status: 200 x 348, failed x 1
2versions seen: 4.0 x 101, 4.1 x 247

Version 4.0 and 4.1 answered side by side for about three seconds, and then only 4.1. That is the difference from Parts 2 and 3. There, Terraform replaced the containers and the site was down for a moment. Here the site stayed up.

Kubernetes replaced the pods one at a time while the Service kept serving. Terraform changed only the image tagScroll sideways, or tap the diagram to open it full size

Kubernetes replaced the pods one at a time while the Service kept serving. Terraform changed only the image tag

I want to be exact: it was not perfect. One request out of 349 failed, about 12 seconds into the run, as the old pods were being stopped. I did not investigate why. A request that is already in flight when its pod is stopped can fail, and the usual fix is to let a pod finish its requests before it exits. This is much better than replacing containers, but it is not magic.

Version 4.1 with the new card. The table also lists the pods that no longer exist, because their counts live in the database

Version 4.1 with the new card. The table also lists the pods that no longer exist, because their counts live in the database

Step 6: break one copy

A pod that is running but broken is the hardest case. I picked one pod, opened a tunnel to it with kubectl port-forward, and called its /break address:

CODE
1$ curl localhost:9000/break
2"this copy is now broken"
3
4$ curl -s -o /dev/null -w "%{http_code}" localhost:9000/
5500

While a program sent requests through the Service, I watched the pods every two seconds. This is what I saw, with the pod's name shortened to its last five letters and its restart count in brackets:

CODE
1+6s   6xnr2=1/1(r0)  ...other four 1/1   endpoints: 5
2+9s   6xnr2=0/1(r0)  ...other four 1/1   endpoints: 4
3+15s  6xnr2=0/1(r0)  ...other four 1/1   endpoints: 4
4+17s  6xnr2=1/1(r1)  ...other four 1/1   endpoints: 5

In order:

  1. Within a few seconds of breaking it, the readiness probe failed twice. The pod went from 1/1 to 0/1, and Kubernetes took it out of the Service. The number of endpoints fell from 5 to 4. Visitors stopped reaching it.
  2. Roughly a dozen seconds after I broke it, the liveness probe had failed three times. Kubernetes restarted the container. The restart count went from 0 to 1, and the pod became 1/1 again, so the endpoints returned to 5. The restart reset the broken flag, because the flag only lives in the running program.

Of the 395 requests sent during this time, 391 succeeded and 4 failed with HTTP 500. They were the requests that reached the broken pod in the first second, before Kubernetes removed it. Then I asked Terraform:

CODE
1No changes. Your infrastructure matches the configuration.

Again, Terraform saw nothing wrong, because as far as it is concerned the Deployment is exactly as declared. A pod that is running but unhealthy is a runtime problem, and the probes handle it.

Step 7: destroy

PROMPT
1terraform destroy
CODE
1kind_cluster.demo: Destruction complete after 0s
2
3Destroy complete! Resources: 12 destroyed.

Docker Desktop showed an empty Containers list:

After destroy, Docker Desktop had no containers left: the kind node and the database were both gone

After destroy, Docker Desktop had no containers left: the kind node and the database were both gone

The cluster, the namespace, the Deployment, the database container, the volume, the web image and the generated password all went. The mssql/server image stayed in my local Docker because I set keep_locally = true on it, as in Part 3. The cluster's entry was also removed from my ~/.kube/config. One thing was left behind: the Docker network called kind, which kind creates. I removed it by hand with docker network rm kind.

Who did what

What happenedWho dealt with it
Create the cluster, database, Secret, Deployment and ServiceTerraform
A pod was deletedKubernetes, in about a second. Terraform saw no difference
The Deployment was deletedTerraform, at the next apply. Kubernetes did not know it was meant to exist
Scale from 3 to 5Terraform changed a number. Kubernetes started the pods
New codeTerraform changed the image tag. Kubernetes did the rolling update
A pod brokeKubernetes took it out of the Service and restarted it. Terraform saw nothing

Where this falls short

  • One state, one file. I created the cluster and the objects inside it in one configuration. The Kubernetes provider is configured from the cluster that Terraform creates in the same run, which can be fragile. Real projects usually create the cluster in one configuration and deploy the workloads from another.
  • Terraform is not the usual way to deploy apps. Many teams use YAML, Helm or a GitOps tool for the objects in the cluster, and Terraform only for the cluster and the infrastructure around it. My 2021 Kubernetes post shows the YAML way.
  • The image loading is a shortcut. I load the web image into the node with docker save and ctr. A real cluster pulls images from a registry.
  • The Service is local. A node port published on my laptop is not how a cloud cluster is exposed. There you would use a load balancer or an ingress.
  • The database sits outside the cluster. That was forced by the Intel-only image, but it is also common. Running a database inside Kubernetes needs persistent volumes and more care.
  • One node, one laptop. This shows how the pieces behave. It does not give real availability.
  • The leftover network. Terraform did not remove Docker's kind network, so I did.
  • The secret is in the state file. The same warning as in Part 3 applies, and Part 6 shows where the state can live instead.

Part 5 takes this further: it runs dev, UAT and prod from one shared module on this kind of cluster, and moves a change through them.

Everything in this post ran on Docker Desktop on my own machine, with Terraform 1.17.2, the tehcyx/kind provider 0.13.0, the hashicorp/kubernetes provider 3.6.0, the kreuzwerker/docker provider 3.9.0, the hashicorp/random provider 3.9.1, a kind node running Kubernetes 1.37.0, and Microsoft's public .NET 10 and mssql/server:2022-latest images.