Terraform on Your Laptop (Part 7)

Neil Haddley • November 30, 2026

Five Terraform odds and ends, tried on the Kubernetes environments from the series: for_each instead of count, terraform test, a pipeline with an approval gate before prod, a data source that reads another directory's state, and terraform import.

DevOpsKubernetesTerraformterraformkubernetesfor-eachterraform-testci-cd

Six posts in, a few questions kept coming up that did not fit anywhere. Each one belongs to a moment in the series, so this post takes them in turn and points back to where they would have fitted:

  • for_each, the other way to make several copies, which Part 2 did with count.
  • terraform test, for the shared module from Part 5.
  • A pipeline, which Part 5 described and did not build.
  • A data source, to remove the kubeconfig file that Part 6 had to hand to a teammate.
  • terraform import, for the container my killed apply orphaned in Part 6.

I ran everything on Docker Desktop on my Mac with Terraform 1.17.2. The module, environments and remote state are the ones from Parts 5 and 6, with the module at a new version, v1.3.0. One piece I could not test: I did not run any workflow on GitHub, and I say where that matters.

for_each instead of count

In Part 2 I made three copies of the site with count, and each copy was found by its position: [0], [1], [2]. That works while the copies are interchangeable. Here is what happens when they are not. I gave each copy its own name, colour and port, in a list:

HCL
1variable "copies" {
2  type = list(object({
3    name  = string
4    color = string
5    port  = number
6  }))
7  default = [
8    { name = "blue", color = "#2563eb", port = 8080 },
9    { name = "green", color = "#16a34a", port = 8081 },
10    { name = "amber", color = "#d97706", port = 8082 },
11  ]
12}
HCL
1resource "docker_container" "site" {
2  count = length(var.copies)
3  name  = "terraform-demo-site-${var.copies[count.index].name}"
4  image = docker_image.site.image_id
5
6  env = [
7    "SITE_TITLE=Copy ${var.copies[count.index].name}",
8    "SITE_COLOR=${var.copies[count.index].color}",
9  ]
10
11  ports {
12    internal = 8080
13    external = var.copies[count.index].port
14  }
15}

The three containers ran. Then I removed the middle one, green, from the list and asked for a plan:

CODE
1# docker_container.site[1] must be replaced
2    ~ name     = "terraform-demo-site-green" -> "terraform-demo-site-amber" # forces replacement
3    ~ external = 8081 -> 8082 # forces replacement
4# docker_container.site[2] will be destroyed
5    # (because index [2] is out of range for count)
6
7Plan: 1 to add, 0 to change, 2 to destroy.

Position [1] now holds amber, so Terraform replaces the green container with an amber one, and then destroys the old amber at position [2], which nobody asked to touch. I removed one copy and Terraform wanted to rebuild two.

for_each finds each copy by a name instead. The copies live in a map:

HCL
1variable "copies" {
2  type = map(object({
3    color = string
4    port  = number
5  }))
6  default = {
7    blue  = { color = "#2563eb", port = 8080 }
8    green = { color = "#16a34a", port = 8081 }
9    amber = { color = "#d97706", port = 8082 }
10  }
11}
HCL
1resource "docker_container" "site" {
2  for_each = var.copies
3  name     = "terraform-demo-site-${each.key}"
4  image    = docker_image.site.image_id
5
6  env = [
7    "SITE_TITLE=Copy ${each.key}",
8    "SITE_COLOR=${each.value.color}",
9  ]
10
11  ports {
12    internal = 8080
13    external = each.value.port
14  }
15}

I removed green from the map in the same way:

CODE
1# docker_container.site["green"] will be destroyed
2    # (because key ["green"] is not in for_each map)
3
4Plan: 0 to add, 0 to change, 1 to destroy.
Removing the middle copy. With count Terraform replaces one copy and destroys another. With for_each it destroys only the one I removedScroll sideways, or tap the diagram to open it full size

Removing the middle copy. With count Terraform replaces one copy and destroys another. With for_each it destroys only the one I removed

Docker Desktop showed the same thing. With all three copies running, then after the removal:

Three copies, each named by its key

Three copies, each named by its key

After removing green. blue and amber kept the container IDs they had before, so Terraform did not touch them

After removing green. blue and amber kept the container IDs they had before, so Terraform did not touch them

Use count for a number of identical copies, such as three web pods that differ only by name. Use for_each when each copy has its own identity, and a copy might be added or removed on its own.

terraform test for the shared module

The module from Part 5 is what every environment runs, so a mistake in it reaches dev, UAT and prod. terraform test runs checks against a configuration, and it is a good gate before a module version is tagged and promoted.

First I made the module reject bad inputs. The environment name becomes a Kubernetes namespace and a Docker name, so it has to be a valid one:

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  validation {
6    condition     = can(regex("^[a-z][a-z0-9-]{0,20}$", var.environment))
7    error_message = "The environment must start with a lower-case letter and use only lower-case letters, digits and hyphens, up to 21 characters, because it becomes a Kubernetes namespace and a Docker name."
8  }
9}

I added a similar rule for the number of pods, 1 to 10. Then I wrote the tests, in a file in the module's tests folder. They plan the module against mocked providers, so they need no Docker and no cluster:

HCL
1# These tests plan the module against mocked providers, so they need no Docker and no cluster.
2mock_provider "docker" {}
3mock_provider "kubernetes" {}
4mock_provider "random" {}
5
6variables {
7  environment = "uat"
8  site_title  = "Shop (UAT)"
9  site_color  = "#7c3aed"
10  instances   = 2
11  node_port   = 30280
12  host_port   = 8280
13}
14
15run "names_follow_the_environment" {
16  command = plan
17
18  assert {
19    condition     = kubernetes_namespace_v1.env.metadata[0].name == "uat"
20    error_message = "The namespace should be named after the environment."
21  }
22
23  assert {
24    condition     = docker_container.db.name == "uat-db" && docker_volume.sqldata.name == "uat-sqldata"
25    error_message = "The database container and volume should start with the environment name."
26  }
27}
28
29run "pods_match_instances" {
30  command = plan
31
32  assert {
33    condition     = tonumber(kubernetes_deployment_v1.site.spec[0].replicas) == 2
34    error_message = "The Deployment should run as many pods as the instances input."
35  }
36}
37
38run "service_uses_the_node_port" {
39  command = plan
40
41  assert {
42    condition     = kubernetes_service_v1.site.spec[0].port[0].node_port == 30280
43    error_message = "The Service should listen on the node port that the environment passes."
44  }
45}
46
47run "rejects_a_bad_environment_name" {
48  command = plan
49
50  variables {
51    environment = "Prod Env"
52  }
53
54  expect_failures = [var.environment]
55}
56
57run "rejects_too_many_pods" {
58  command = plan
59
60  variables {
61    instances = 11
62  }
63
64  expect_failures = [var.instances]
65}

Three of the runs check what the module builds: that names follow the environment, that the Deployment has as many pods as the instances input, and that the Service uses the node port. The last two check that bad inputs are refused, with expect_failures. I ran them:

PROMPT
1terraform test
CODE
1tests/shop.tftest.hcl... in progress
2  run "names_follow_the_environment"... pass
3  run "pods_match_instances"... pass
4  run "service_uses_the_node_port"... pass
5  run "rejects_a_bad_environment_name"... pass
6  run "rejects_too_many_pods"... pass
7tests/shop.tftest.hcl... tearing down
8tests/shop.tftest.hcl... pass
9
10Success! 5 passed, 0 failed.

A test only helps if it fails when something is wrong. So I planted a bug in a scratch copy of the module: I hard-coded the namespace name as "prod" instead of using the environment. The test run failed:

CODE
1  run "names_follow_the_environment"... fail
2
3Error: Test assertion failed
4
5  on tests/shop.tftest.hcl line 19, in run "names_follow_the_environment":
6  19:     condition     = kubernetes_namespace_v1.env.metadata[0].name == "uat"
7    │ Diff:
8    │ - "prod"
9    │ + "uat"
10
11The namespace should be named after the environment.
12
13Failure! 4 passed, 1 failed.

The exit code was 1, which is what stops a pipeline. The failure names the test, the line, the actual value and the expected one, and the message I wrote for it.

I tagged the module v1.3.0 with the validation, the tests and one small visible change, a card showing the opening hours. Next, the release.

A pipeline, with a gate before prod

Part 5 described where a pipeline fits. A pipeline runs the same stages every time, and it stops at the first stage that fails. I wrote the stages as one script, so that they run the same on my laptop and on a CI runner. It has two modes: check, which runs on every change, and release, which runs after the change is merged:

BASH
1#!/usr/bin/env bash
2# The stages of the pipeline, in one script so that they run the same on a laptop and on a CI runner.
3#
4#   ci/pipeline.sh check   environments/dev      format, validate, test, plan (saves the plan)
5#   ci/pipeline.sh release environments/prod     approval gate, apply the saved plan, smoke test
6#
7# Needs: PG_CONN_STR for the directory (a CI secret), and APPROVED=yes to release to prod.
8set -euo pipefail
9
10mode="$1"
11dir="$2"
12name="$(basename "$dir")"
13root="$(cd "$(dirname "$0")/.." && pwd)"
14
15stage() { printf '\n== stage: %s\n' "$1"; }
16
17case "$mode" in
18  check)
19    stage "format"
20    terraform fmt -check -recursive "$root"
21
22    stage "validate"
23    (cd "$root/$dir" && terraform init -input=false -no-color > /dev/null && terraform validate -no-color)
24
25    stage "test"
26    (cd "$root/modules/shop" && terraform init -input=false -no-color > /dev/null && terraform test -no-color)
27
28    stage "plan"
29    (cd "$root/$dir" &&
30      terraform plan -input=false -no-color -out=tfplan > /dev/null &&
31      terraform show -no-color tfplan > plan.txt &&
32      grep -E '^(Plan:|No changes)' plan.txt)
33    echo "plan saved as $dir/tfplan and $dir/plan.txt"
34    ;;
35
36  release)
37    stage "approval"
38    if [ "$name" = "prod" ] && [ "${APPROVED:-}" != "yes" ]; then
39      echo "prod needs an approval. Stopping here. Nothing has been applied."
40      exit 2
41    fi
42    echo "approved"
43
44    stage "apply"
45    (cd "$root/$dir" && terraform apply -input=false -no-color tfplan | grep -E '^(Apply complete|Error)')
46
47    stage "smoke test"
48    url="$(cd "$root/$dir" && terraform output -raw url)"
49    curl -fsS "$url" | grep -o "Environment: <b>[^<]*</b> &nbsp; Site version: <b>[^<]*" | sed 's/<[^>]*>//g; s/&nbsp;//g'
50    ;;
51
52  *)
53    echo "usage: ci/pipeline.sh check|release <directory>" >&2
54    exit 64
55    ;;
56esac

The script is the pipeline. The stages do what they say:

StageWhat it catches
formatUntidy files, with a clear list of which ones
validateTypos and mistakes in the configuration
testA broken module
planThe change itself, saved as a file the reviewer reads
approvalProd only: a person has to say yes
applyApplies the saved plan from the plan stage, not a new one
smoke testThe site answers with the version I expected

I ran it on Part 6's setup, with the state in PostgreSQL. The connection string for each directory, PG_CONN_STR, is what a CI system would keep as a secret.

A badly formatted change stops at the first stage. Dev and UAT pass every stage. Prod stops at the approval gate until a person approvesScroll sideways, or tap the diagram to open it full size

A badly formatted change stops at the first stage. Dev and UAT pass every stage. Prod stops at the approval gate until a person approves

A bad change stops early. I made a deliberate formatting mistake in prod's file and ran check. It stopped at the first stage and listed the file:

CODE
1== stage: format
2environments/prod/main.tf
3pipeline exit code: 3

Validate, test and plan never ran.

Dev and UAT release. I moved dev's pin to v1.3.0 and ran check and then release. Every stage passed, and UAT did the same:

CODE
1== stage: test
2Success! 5 passed, 0 failed.
3
4== stage: plan
5Plan: 2 to add, 1 to change, 2 to destroy.
6plan saved as environments/dev/tfplan and environments/dev/plan.txt
7
8== stage: approval
9approved
10
11== stage: apply
12Apply complete! Resources: 2 added, 1 changed, 2 destroyed.
13
14== stage: smoke test
15Environment: dev  Site version: 1.3.0

Prod stops at the gate. I moved prod's pin and ran check, which passed and saved a plan. The reviewer reads plan.txt: the image replaced, the Deployment updated in place, the image-loading step replaced. Then I ran release without approval:

CODE
1== stage: approval
2prod needs an approval. Stopping here. Nothing has been applied.
3exit code: 2

Prod still served version 1.2.0. Then I ran it again with APPROVED=yes, which stands in for a reviewer's click:

CODE
1== stage: approval
2approved
3
4== stage: apply
5Apply complete! Resources: 2 added, 1 changed, 2 destroyed.
6
7== stage: smoke test
8Environment: prod  Site version: 1.3.0

The same stages as a GitHub Actions workflow. Real teams keep these in their CI system. This is the same pipeline written for GitHub Actions. I did not run it on GitHub. My Docker and my cluster are on this laptop, so the jobs need a self-hosted runner, and I did not set one up. I checked only that the file is valid YAML:

YAML
1# The same stages as ci/pipeline.sh, written for GitHub Actions.
2# I ran the script on my laptop. I did not run this workflow on GitHub.
3name: terraform
4
5on:
6  pull_request:
7    paths: ["modules/**", "environments/**", "platform/**"]
8  push:
9    branches: [main]
10    paths: ["modules/**", "environments/**"]
11
12jobs:
13  check:
14    runs-on: self-hosted # needs Docker and the cluster, so a hosted runner would not do
15    strategy:
16      matrix:
17        include:
18          - { directory: environments/dev, secret: PG_CONN_STR_DEV }
19          - { directory: environments/uat, secret: PG_CONN_STR_UAT }
20          - { directory: environments/prod, secret: PG_CONN_STR_PROD }
21    env:
22      PG_CONN_STR: ${{ secrets[matrix.secret] }}
23    steps:
24      - uses: actions/checkout@v4
25      - uses: hashicorp/setup-terraform@v3
26        with:
27          terraform_version: 1.17.2
28      - run: ci/pipeline.sh check ${{ matrix.directory }}
29      - uses: actions/upload-artifact@v4
30        with:
31          name: plan-${{ matrix.secret }}
32          path: |
33            ${{ matrix.directory }}/tfplan
34            ${{ matrix.directory }}/plan.txt
35
36  release:
37    if: github.event_name == 'push'
38    needs: check
39    runs-on: self-hosted
40    strategy:
41      max-parallel: 1 # dev, then uat, then prod
42      matrix:
43        include:
44          - { directory: environments/dev, secret: PG_CONN_STR_DEV, gate: preproduction }
45          - { directory: environments/uat, secret: PG_CONN_STR_UAT, gate: preproduction }
46          - { directory: environments/prod, secret: PG_CONN_STR_PROD, gate: production }
47    environment: ${{ matrix.gate }} # the "production" environment has required reviewers
48    env:
49      PG_CONN_STR: ${{ secrets[matrix.secret] }}
50      APPROVED: "yes" # reached only after the environment's reviewers approve
51    steps:
52      - uses: actions/checkout@v4
53      - uses: hashicorp/setup-terraform@v3
54        with:
55          terraform_version: 1.17.2
56      - uses: actions/download-artifact@v4
57        with:
58          name: plan-${{ matrix.secret }}
59          path: ${{ matrix.directory }}
60      - run: ci/pipeline.sh release ${{ matrix.directory }}

In GitHub, an environment can be set to require reviewers, and the idea is that the production job then pauses until someone approves, as APPROVED does in my script. I have not seen that behaviour work, so treat the workflow as a starting point.

A data source: read another directory's state

A data source reads something that already exists and does not create it. The most useful one here is terraform_remote_state, which reads another directory's outputs.

In Part 6 the environments reached the cluster through a kubeconfig file, found by a path to the platform directory. A teammate had to be given that file separately. Instead, the platform can publish what the environments need as outputs:

HCL
1# What the environments need to reach the cluster. They read these from this directory's state.
2output "endpoint" {
3  value = kind_cluster.shop.endpoint
4}
5
6output "cluster_ca_certificate" {
7  value     = kind_cluster.shop.cluster_ca_certificate
8  sensitive = true
9}
10
11output "client_certificate" {
12  value     = kind_cluster.shop.client_certificate
13  sensitive = true
14}
15
16output "client_key" {
17  value     = kind_cluster.shop.client_key
18  sensitive = true
19}

And dev can read them from the platform's remote state:

HCL
1variable "platform_state_conn" {
2  type        = string
3  sensitive   = true
4  description = "A connection string that may read the platform directory's state."
5}
6
7# The cluster belongs to the platform directory. Read its details from that directory's state.
8data "terraform_remote_state" "platform" {
9  backend = "pg"
10
11  config = {
12    conn_str             = var.platform_state_conn
13    schema_name          = "platform"
14    skip_schema_creation = true
15    skip_table_creation  = true
16    skip_index_creation  = true
17  }
18}
19
20provider "kubernetes" {
21  host                   = data.terraform_remote_state.platform.outputs.endpoint
22  cluster_ca_certificate = data.terraform_remote_state.platform.outputs.cluster_ca_certificate
23  client_certificate     = data.terraform_remote_state.platform.outputs.client_certificate
24  client_key             = data.terraform_remote_state.platform.outputs.client_key
25}

First without permission. In Part 6 each directory's role can see only its own schema, so dev's role could not read the platform's state. The plan said so:

CODE
1Error: Error loading state error
2error loading the remote state: pq: permission denied for schema platform

Then a read-only grant. I gave the three environment roles read access to the platform's state, and nothing more:

HCL
1resource "terraform_data" "platform_read" {
2  triggers_replace = [docker_container.pg.id]
3  depends_on       = [terraform_data.role]
4
5  provisioner "local-exec" {
6    command = "docker exec -e PGPASSWORD=\"$ADMIN_PASSWORD\" tfstate-db psql -U admin -d terraform_state -v ON_ERROR_STOP=1 -c \"GRANT USAGE ON SCHEMA platform TO dev, uat, prod; GRANT SELECT ON platform.states TO dev, uat, prod;\""
7
8    environment = {
9      ADMIN_PASSWORD = random_password.admin.result
10    }
11  }
12}

The plan in dev then said No changes, and it now reaches the cluster through the platform's state. I checked what the dev role can do:

CODE
1read platform state:   1 row visible
2write platform state:  ERROR:  permission denied for table states
3read prod state:       ERROR:  permission denied for schema prod

It can read the platform's state, and it cannot change it or look at another environment's.

A teammate without the kubeconfig. I committed this and made a fresh clone, as in Part 6. This time there was no kubeconfig file in it at all. In the clone's dev directory:

CODE
1Successfully configured the backend "pg"! Terraform will automatically
2use this backend unless the backend configuration changes.
3
4No changes. Your infrastructure matches the configuration.

The file is no longer needed, and neither is a path between directories. Two things to know. The platform's outputs now contain the cluster's client certificate and key, so anyone who can read that state has cluster access, and the read grant above is a real decision. And the endpoint is 127.0.0.1, so this works on my machine, not a different one. Other data sources exist, such as ones that look up a Docker network or a cloud resource by name. I only used this one.

terraform import: adopt what already exists

Sometimes the real world contains something that Terraform's state does not know about. terraform import adds it to the state, so Terraform manages it from then on. I used the config-driven form, an import block, which shows up in the plan like any other change.

A clean case: the database volume. The volume holds the data, so it is the last thing I would want Terraform to recreate. I told Terraform to forget it, which leaves the volume itself untouched:

CODE
1$ terraform state rm module.shop.docker_volume.sqldata
2Removed module.shop.docker_volume.sqldata

The plan wanted to create it again: Plan: 1 to add, 0 to change, 0 to destroy. Then I added an import block:

HCL
1import {
2  to = module.shop.docker_volume.sqldata
3  id = "dev-sqldata"
4}
CODE
1# module.shop.docker_volume.sqldata will be imported
2
3Plan: 1 to import, 0 to add, 0 to change, 0 to destroy.
4
5Apply complete! Resources: 1 imported, 0 added, 0 changed, 0 destroyed.

A plan afterwards said No changes. That is import working as it should: the resource is adopted, and nothing is created or destroyed.

A case where it does not help: the orphaned container. In Part 6 my killed apply left a database container that Terraform did not know about, and I deleted it. This time I tried to adopt it. I removed the stale entry from the state, wrote an import block with the container's ID, and planned:

CODE
1# module.shop.docker_container.db must be replaced
2# (imported from "5b993316c9e8...")
3# Warning: this will destroy the imported resource
4    + env = (sensitive value) # forces replacement
5    + networks_advanced { # forces replacement
6    + volumes { # forces replacement
7
8Plan: 1 to import, 2 to add, 0 to change, 2 to destroy.

The provider could not fill in the container's environment, network and volumes from the one that already existed, so it saw a difference in each and wanted to replace the very container I was adopting. That defeats the purpose. I did not apply it. I removed the import block, deleted the orphan, and applied normally: No changes afterwards, and the site answered on 1.3.0.

The lesson is about the resource type. Import is clean when a resource's settings can be read back and match the configuration, as with the volume. For a container with many settings it may not be. Run the plan before you apply an import, and read it.

Where each one fits

WhatWhere I would use it
for_eachCopies with their own identity, which might be added or removed one at a time
terraform testA shared module, before each version is tagged
A pipelineEvery change, with a gate before prod
A data sourceReading what another directory or system owns, without copying it
terraform importAdopting something that exists and whose settings round-trip

Where this falls short

  • No workflow ran on GitHub. I ran the pipeline as a script on my laptop. The GitHub Actions file is valid YAML and nothing more. I did not test its expressions, its secrets or the approval behaviour.
  • The approval is simulated. APPROVED=yes is a variable I set, not a person's review.
  • The tests are mocked. They check what the module asks for, not what Docker or Kubernetes does. A real apply test would cover more and cost more.
  • The data source depends on a read grant and on one machine. It exposes cluster credentials in the platform's outputs, and the endpoint works only on this laptop.
  • Import for a container did not work. I tried two resources from the Docker provider, a volume and a container, and they behaved differently. Other providers and other resources may behave differently again.
  • The import block, not the older command. I did not run the terraform import command itself.
  • Cloud backends are still untested. Everything here used PostgreSQL for state, as in Part 6.

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, the official postgres:17-alpine image, a kind node running Kubernetes 1.37.0, and Microsoft's public .NET 10 and mssql/server:2022-latest images.