Terraform on Your Laptop (Part 5)

Neil Haddley • November 30, 2026

Terraform environments on Kubernetes: dev, UAT and prod namespaces deployed from one shared module at pinned versions, with a change moving through UAT feedback to a release and a rollback.

DevOpsKubernetesTerraformterraformkubernetesmodulesenvironmentsuat

In Part 4 I used Terraform to create a Kubernetes cluster and deploy the site into it, and I watched Kubernetes keep the pods running. That was one copy of everything. A real project has several environments: somewhere to build a change, somewhere for testers to try it, and the live system. The hard part is not creating three copies. It is moving a change through them in order, without ever touching the live system by accident.

In this post I run the C# site and its SQL Server database from Part 4 as three environments: dev, UAT and prod. They share one reusable module. Each environment is a namespace in one Kubernetes cluster, deployed from its own directory with its own Terraform state, and it pins the module to a tagged version. Then I act out a release. A change goes to dev, then to UAT, where testers give feedback. The feedback goes back to dev, a fixed version returns to UAT, and only the version the testers accepted goes to prod. At the end I roll prod back and forward again.

I ran everything on Docker Desktop on my Mac with Terraform 1.17.2. The UAT feedback in this post is simulated: I wrote the comments myself, to show how feedback flows through the process. The cluster, the environments, the versions and everything Terraform and Kubernetes did are real.

A change moves from dev to UAT. UAT feedback goes back to dev, and only the fixed version is released to prodScroll sideways, or tap the diagram to open it full size

A change moves from dev to UAT. UAT feedback goes back to dev, and only the fixed version is released to prod

The layout: a platform, a module and one directory per environment

I used a layout with the cluster in one folder, the reusable blueprint in another, and one folder for each live environment:

CODE
1shop-infra/
2  platform/
3    main.tf                creates the Kubernetes cluster, once
4  modules/
5    shop/                  the reusable blueprint
6      main.tf              database, image, namespace, Secret, Deployment, Service
7      variables.tf         what an environment can choose
8      outputs.tf           what an environment gets back
9      versions.tf          which providers it needs
10      app/                 the C# site and its Dockerfile
11      db/init.sql          the T-SQL stored procedures
12  environments/
13    dev/main.tf            1 pod
14    uat/main.tf            2 pods
15    prod/main.tf           3 pods

Each folder with a main.tf that I run is a Terraform root: a place where I run terraform plan and terraform apply. Each one has its own state file, so what Terraform knows about dev is kept apart from what it knows about prod, and both are kept apart from what it knows about the cluster. A command run in environments/dev cannot change prod, because prod's resources are not in dev's state.

A command run in dev updates only dev's state. A plan in UAT or prod reports no changes, and the platform directory is untouchedScroll sideways, or tap the diagram to open it full size

A command run in dev updates only dev's state. A plan in UAT or prod reports no changes, and the platform directory is untouched

In Part 4 I created the cluster and the objects in it from one file, and I listed that as a limit. Here the cluster has its own directory, so the environments simply deploy into a cluster that already exists. The usual setup for real clusters looks like this too: one team creates the platform, and others deploy onto it.

A CI/CD article from Stategraph (a company that sells Terraform tooling, so read it with that in mind) describes the two usual choices for environments: separate directories, each its own root module with its own backend and variables, or one root module with several workspaces that share both. It says workspaces work for a few near-identical environments, but their shared backend and root module become a liability when environments genuinely differ. Separate directories cost some duplication and let each environment differ without conditions in every resource. I used separate directories. The article is about pipelines as well, and I come back to that at the end.

You can download the files, which are the same as the ones I ran: platform/main.tf, modules/shop/main.tf, variables.tf, outputs.tf, versions.tf, Program.cs, init.sql, and the three environments: dev, uat and prod. The module files are the final version, 1.2.0.

The platform: one cluster

The platform directory creates a single-node kind cluster, as in Part 4. The difference is that it publishes three ports, one for each environment, and it writes the cluster's connection file next to its own files instead of into my ~/.kube/config:

HCL
1resource "kind_cluster" "shop" {
2  name            = "shop"
3  kubeconfig_path = "${path.module}/kubeconfig"
4  wait_for_ready  = true
5
6  kind_config {
7    kind        = "Cluster"
8    api_version = "kind.x-k8s.io/v1alpha4"
9
10    node {
11      role = "control-plane"
12
13      extra_port_mappings {
14        container_port = 30180
15        host_port      = 8180
16      }
17
18      extra_port_mappings {
19        container_port = 30280
20        host_port      = 8280
21      }
22
23      extra_port_mappings {
24        container_port = 30380
25        host_port      = 8380
26      }
27    }
28  }
29}
PROMPT
1terraform plan -out=tfplan
2terraform apply tfplan

The plan was 1 to add, and the cluster took 27 seconds. kubectl against the new file showed one node:

CODE
1NAME                 STATUS   ROLES           AGE   VERSION
2shop-control-plane   Ready    control-plane   20s   v1.37.0

My own ~/.kube/config still had no contexts, so nothing of mine changed. The three environments read the cluster's connection details from the file the platform wrote.

The module

The module is Part 4's stack with nothing fixed. An environment chooses six things, and a seventh, cluster_node, has a default that matches the platform:

HCL
1variable "environment" {
2  type        = string
3  description = "Short name of the environment, such as dev or prod. It names the namespace and prefixes the database resources."
4}
5
6variable "site_title" {
7  type    = string
8  default = "Hello from Terraform"
9}
10
11variable "site_color" {
12  type    = string
13  default = "#2563eb"
14}
15
16variable "instances" {
17  type        = number
18  default     = 1
19  description = "How many pods of the web site to run."
20}
21
22variable "node_port" {
23  type        = number
24  description = "The cluster port that this environment's Service listens on."
25}
26
27variable "host_port" {
28  type        = number
29  description = "The port on my machine that the platform maps to node_port. Used only for the output."
30}
31
32variable "cluster_node" {
33  type        = string
34  default     = "shop-control-plane"
35  description = "Name of the Docker container that is the cluster's node. The web image is loaded into it."
36}

The module creates the same things as Part 4, one set for each environment:

  • The database, a SQL Server container in Docker, outside the cluster, with its own volume and generated password. Its name starts with the environment, and it joins the kind network, so the pods can reach it by name:
HCL
1resource "docker_container" "db" {
2  name  = "${var.environment}-db"
3  ...
4  networks_advanced {
5    name = "kind"
6  }
7  ...
8}
  • The web image, built from the module's own app folder and loaded into the cluster's node.
  • A namespace named after the environment, so every Kubernetes object for that environment lives in it:
HCL
1resource "kubernetes_namespace_v1" "env" {
2  metadata {
3    name = var.environment
4  }
5}
  • A Secret with the connection string, and a Deployment with the same rolling-update settings and health probes as Part 4. The Deployment's replica count comes from instances.
  • A Service that listens on the environment's own node port, which the platform published:
HCL
1resource "kubernetes_service_v1" "site" {
2  metadata {
3    name      = "site"
4    namespace = kubernetes_namespace_v1.env.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   = var.node_port
18    }
19  }
20}

An environment: a module call that pins a version

An environment directory is small. This is UAT:

HCL
1terraform {
2  required_providers {
3    docker = {
4      source  = "kreuzwerker/docker"
5      version = "~> 3.0"
6    }
7    kubernetes = {
8      source  = "hashicorp/kubernetes"
9      version = "~> 3.0"
10    }
11  }
12}
13
14provider "docker" {}
15
16# The cluster is created by the platform directory, which writes this kubeconfig file.
17provider "kubernetes" {
18  config_path = "${path.module}/../../platform/kubeconfig"
19}
20
21module "shop" {
22  source = "git::file:///path/to/shop-infra//modules/shop?ref=v1.2.0"
23
24  environment = "uat"
25  site_title  = "Shop (UAT)"
26  site_color  = "#7c3aed"
27  instances   = 2
28  node_port   = 30280
29  host_port   = 8280
30}
31
32output "url" {
33  value = module.shop.url
34}

The important line is ?ref=v1.2.0 at the end of the module source. It pins the environment to the tag v1.2.0 of the module's git repository. The path is shortened here: I ran this against a local repository, and on a team the source would be an https or ssh address. Dev and prod are the same file with different values:

devUATprod
environment"dev""uat""prod"
site_title"Shop (dev)""Shop (UAT)""Spring Sale"
site_colorbluepurplegreen
instances123
node_port / host_port30180 / 818030280 / 828030380 / 8380

Step 0: create all three environments at version 1.0.0

I tagged the first version of the module v1.0.0 and pointed all three environments at it. In each directory I ran:

PROMPT
1terraform init
2terraform plan -out=tfplan
3terraform apply tfplan

init downloads the module at the pinned tag. I saved the plan to a file with -out=tfplan and applied that file, so what runs is exactly what I reviewed. The Stategraph article recommends the same, since a fresh plan at apply time can differ from the one a reviewer approved. Each environment's plan was 11 to add. Then I asked Kubernetes what was running:

CODE
1$ kubectl get pods -A
2NAMESPACE   NAME                    READY   STATUS    RESTARTS   AGE
3dev         site-cd687f468-tcjsw    1/1     Running   0          30s
4prod        site-78fbc7f5dc-8hxbz   1/1     Running   0          7s
5prod        site-78fbc7f5dc-dh67h   1/1     Running   0          7s
6prod        site-78fbc7f5dc-trr2j   1/1     Running   0          7s
7uat         site-5bdb4db7bb-p2ffw   1/1     Running   0          16s
8uat         site-5bdb4db7bb-zjwkp   1/1     Running   0          16s
9
10$ kubectl get svc -A
11NAMESPACE   NAME   TYPE       CLUSTER-IP     PORT(S)
12dev         site   NodePort   10.96.61.58    80:30180/TCP
13prod        site   NodePort   10.96.33.104   80:30380/TCP
14uat         site   NodePort   10.96.75.248   80:30280/TCP

One pod for dev, two for UAT and three for prod, each environment in its own namespace. Docker Desktop shows only the cluster's node and the three databases, because the pods run inside the node:

Docker Desktop: the cluster node, which publishes the three environment ports, and one SQL Server container for each environment. The pods are inside the node

Docker Desktop: the cluster node, which publishes the three environment ports, and one SQL Server container for each environment. The pods are inside the node

Round 1: build in dev, then promote to UAT

I changed the module and tagged it v1.1.0. The release added a free-delivery banner to the page and changed the product stored procedure to list the dearest products first:

CODE
1-     ORDER BY Name;
2+     ORDER BY Price DESC;

Then I moved dev's pin from v1.0.0 to v1.1.0. That is the whole change to the dev environment:

CODE
1-  source = "git::file:///path/to/shop-infra//modules/shop?ref=v1.0.0"
2+  source = "git::file:///path/to/shop-infra//modules/shop?ref=v1.1.0"
One line changes, then a plan, then an apply of that saved plan. These are the numbers from the dev changeScroll sideways, or tap the diagram to open it full size

One line changes, then a plan, then an apply of that saved plan. These are the numbers from the dev change

After terraform init downloaded the new tag, the plan showed what the version change meant for dev:

CODE
1# module.shop.docker_image.site must be replaced
2# module.shop.kubernetes_deployment_v1.site will be updated in-place
3# module.shop.terraform_data.db_schema must be replaced
4# module.shop.terraform_data.load_image must be replaced
5
6Plan: 3 to add, 1 to change, 3 to destroy.

Read it as Kubernetes would. A new image is built and loaded into the cluster, and the schema script is re-run because init.sql changed. The Deployment is changed in place: its image tag moves to the new version. Terraform does not touch the pods. Kubernetes sees the new tag and rolls the pods over, as in Part 4. The database container and its data are not in the plan.

While I applied the saved plan, a program sent a request every tenth of a second to dev. All 197 succeeded, with version 1.0.0 answering at first and 1.1.0 after:

Dev on version 1.1.0, with the free-delivery banner and the products listed dearest first

Dev on version 1.1.0, with the free-delivery banner and the products listed dearest first

Then I asked the other two environments what they thought:

CODE
1uat:  No changes. Your infrastructure matches the configuration.
2prod: No changes. Your infrastructure matches the configuration.

Their pins had not moved, so neither environment had anything to do. Dev can change as often as it likes.

Promoting to UAT is the same one-line change in UAT's directory, from v1.0.0 to v1.1.0. The plan was again 3 to add, 1 to change, 3 to destroy. While I applied it, the same kind of request loop ran against UAT. Of 186 requests, 184 succeeded and 2 failed, about two tenths of a second apart. I did not investigate why. A request that is in flight when an old pod stops can fail, even in a rolling update.

UAT on version 1.1.0, ready for the testers

UAT on version 1.1.0, ready for the testers

UAT feedback (simulated)

The testers looked at UAT for a while. These are the comments I wrote, to stand in for real feedback, and what each led to:

Tester comment (simulated)ChangeWhere
"I almost missed the free-delivery banner."Make the banner a prominent amber panelC#
"Are the prices in dollars? It does not say."Heading becomes "Products (prices in AUD)"C#
"Dearest first is odd for a garden shop. Cheapest first, please."ORDER BY Price ASCT-SQL stored procedure

Two of the three comments change the C# code and one changes a stored procedure. The module carries both kinds of change in one version, so it did not matter which kind each comment was.

Round 2: feedback goes back to dev

I made the three changes in the module, committed them, and tagged the result v1.2.0. The comparison with the previous tag showed the whole change:

CODE
1 modules/shop/app/Program.cs | 6 +++---
2 modules/shop/db/init.sql    | 2 +-
3
4-     ORDER BY Price DESC;
5+     ORDER BY Price ASC;
6-          <div class="card"><b>Products</b>
7+          <div class="card"><b>Products (prices in AUD)</b>

I moved dev to v1.2.0 first, and the plan was 3 to add, 1 to change, 3 to destroy. When dev looked right, I moved UAT to v1.2.0 with the same plan. Of 185 requests sent while it rolled, 183 succeeded and 2 failed. This is what the testers saw the second time:

UAT on version 1.2.0: a prominent banner, prices in AUD, and the cheapest products first

UAT on version 1.2.0: a prominent banner, prices in AUD, and the cheapest products first

The testers accepted it (also simulated). At that moment the three environments were on three different versions: dev and UAT on 1.2.0, and prod still on 1.0.0. That is the point of pinning:

Dev and UAT on version 1.2.0, and prod unchanged on 1.0.0. The live system has not moved through two rounds of change

Dev and UAT on version 1.2.0, and prod unchanged on 1.0.0. The live system has not moved through two rounds of change

Prod's plan at this point said No changes.

Release: prod moves to 1.2.0

The release was a one-line change in prod's directory, from v1.0.0 to v1.2.0:

CODE
1-  source = "git::file:///path/to/shop-infra//modules/shop?ref=v1.0.0"
2+  source = "git::file:///path/to/shop-infra//modules/shop?ref=v1.2.0"

Prod skipped v1.1.0 altogether, because the testers had not accepted it. The plan was the same shape as for the other environments, even though prod has three pods, because the number of pods is Kubernetes's business:

CODE
1Plan: 3 to add, 1 to change, 3 to destroy.

I applied the saved plan while a program sent requests to prod. Of 194 requests, 191 succeeded and 3 failed. The new ReplicaSet ended with three pods and the old one with none:

CODE
1$ kubectl -n prod get rs
2NAME              DESIRED   CURRENT   READY   AGE
3site-56b6d9fc55   3         3         3       20s
4site-78fbc7f5dc   0         0         0       2m48s
Prod on version 1.2.0, released after UAT sign-off. The table also lists the pods that no longer exist, because their visit counts live in the database

Prod on version 1.2.0, released after UAT sign-off. The table also lists the pods that no longer exist, because their visit counts live in the database

Then I ran a plan in all three directories, and all three said No changes. Every environment matched its pinned version.

Rolling back

Every release in this post is a change of pin, so a rollback is the same change in reverse. I moved prod's pin from v1.2.0 back to v1.0.0, the previous release, and applied the plan:

CODE
1Plan: 3 to add, 1 to change, 3 to destroy.
2Apply complete! Resources: 3 added, 1 changed, 3 destroyed.
3
4prod now serves: Site version: 1.0.0

Then I moved the pin forward to v1.2.0 again, with the same plan and apply, and prod served 1.2.0.

Clean up

I destroyed the environments one directory at a time, then the platform. Each terraform destroy removed only its own resources: 11 for prod, 11 for UAT, 11 for dev and 1 for the cluster. Docker's kind network, which the cluster creates, was left behind, as in Part 4, so I removed it by hand.

After the four destroys, Docker Desktop had no containers left. No volumes from the environments remained either

After the four destroys, Docker Desktop had no containers left. No volumes from the environments remained either

What the layout gave me

What I wantedWhat happened
A change must not reach prod by accidentDev and UAT changed twice while prod's plan said No changes
Everything runs the same codeAll three environments used the same module, at tagged versions
Environments may differDifferent names, colours, number of pods and ports, from six inputs
A clear way to promoteA one-line change to the pin, reviewed as a diff
Review what will runA saved plan, applied exactly as saved
Releases that keep the site upKubernetes rolled the pods, and most requests succeeded throughout
A way backThe same one-line change, in reverse
Feedback to improve a change before releasev1.1.0 never reached prod. v1.2.0 did

Where a pipeline fits

I ran every command by hand, and I did not build a pipeline in this post. The Stategraph article is about what a pipeline adds: a plan on every pull request, a saved plan as the reviewed artifact, and an approval step before the apply. With this layout, each environment directory could have its own plan job, and prod's apply could wait for a person to approve it. The article also covers state locking and what happens when a change spans several state files. Read it for those. My steps above are the manual version of that flow. Part 7 builds the pipeline as a script, runs it with a gate before prod, and adds tests for the shared module.

Where this falls short

  • Local state. Each directory's state is a file in that directory. A team keeps each state in a shared, locked place, usually with different credentials for each environment, so a person with dev access cannot touch prod. Part 6 does exactly that.
  • One cluster for all three. Namespaces separate the objects, and they do not separate the cluster. A problem with the cluster itself would affect dev, UAT and prod together. In practice prod often gets its own cluster, or its own account.
  • No approval step. Nothing stopped me from running prod's apply. A pipeline would add that gate.
  • A few failed requests. The rolling updates in UAT and prod lost 2 or 3 requests each, and I did not investigate why. A longer shutdown period for old pods is the usual place to look.
  • The module and the environments share one repository. I did that to keep the post small. Many teams keep the module in its own repository and pin to its tags, which keeps the version history of the blueprint separate from the history of the environments.
  • Coupled directories. The environments read the cluster's connection file by a path to the platform directory. Real setups pass this through a shared store or a managed cluster's own login. Part 7 replaces the file path with a read of the platform's state.
  • The image shortcut. Terraform loads the web image into the node with docker save. A real cluster pulls from a registry.
  • Duplication. Each environment repeats the provider blocks and the module call. That is the price of separate directories, and keeping the real logic in the module keeps it small.
  • A generated password in each state file. The same warning as in Part 3 applies, three times over.

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