Terraform on Your Laptop (Part 6)

Neil Haddley โ€ข November 30, 2026

Remote state and locking on a laptop, for the Kubernetes environments from Part 5: Terraform state moved from local files into PostgreSQL, one schema and one role per directory, tested with a lock clash, a refused credential, a killed apply and a teammate's fresh clone.

DevOpsSQLKubernetesTerraformterraformkubernetesremote-statestate-lockingpostgresql

Four posts in this series said the same thing in different words: "a team would keep the state file in a shared, locked place". In Part 1 I said I would try that. In Part 3 I warned that the state file holds secrets. In Part 5 I gave each environment its own state file, and said that on a team each one needs its own protected home. This post does it.

Until now every state file has been an ordinary file in the directory where I ran Terraform. That is fine for one person on one laptop, and it breaks down in three ways. The state exists on one machine only. Two people can run apply at the same time and overwrite each other. And the file holds generated passwords, so it needs protecting like a secret.

The fix is a remote backend: Terraform keeps the state in a shared service instead of a file, and locks it while a command runs. In this post I move Part 5's four directories (the cluster platform and the dev, UAT and prod environments on Kubernetes) onto a remote backend. Then I try to break it with a lock clash, a refused credential, a killed apply and a teammate's fresh clone.

I ran everything on Docker Desktop on my Mac with Terraform 1.17.2.

Four local state files move into one database. Each directory gets its own schema and its own role, and one role is refused access to another's schemaScroll sideways, or tap the diagram to open it full size

Four local state files move into one database. Each directory gets its own schema and its own role, and one role is refused access to another's schema

Which backend, and why PostgreSQL

On a real team the state usually goes to cloud storage, such as an S3 bucket or an Azure storage account. I wanted something that runs on my laptop with no cloud account. I tried a local S3-compatible server first, and the images would not pull: minio/minio failed to pull from Docker Hub, and the copy on Quay asked for a login. So I used a backend that is built into Terraform and needs only a public image: pg, which stores state in PostgreSQL and uses the database for locking.

The ideas carry over to the cloud backends: state in a shared service, a lock around each command, and separate access for each environment. The details differ, and I note where, at the end.

The state store: created by Terraform, with its own state

Something has to create the database that will hold the state, and it cannot keep its own state in itself. So the state store lives in a small bootstrap directory whose own state stays in a local file. That is the usual answer to the chicken-and-egg problem, and it is the one directory that I would back up carefully.

The bootstrap directory starts a PostgreSQL container, and then it creates one role and one schema for each of my four directories: platform, dev, uat and prod. Each role owns its schema and has no rights on the others. Each schema has one table, states, where that directory's state will live. Here is the part that creates a role:

HCL
1resource "terraform_data" "role" {
2  for_each = local.directories
3
4  triggers_replace = [docker_container.pg.id]
5  depends_on       = [terraform_data.sequence]
6
7  provisioner "local-exec" {
8    command = <<-EOT
9      docker exec -e PGPASSWORD="$ADMIN_PASSWORD" tfstate-db psql -U admin -d terraform_state -v ON_ERROR_STOP=1 -c "
10        CREATE ROLE ${each.key} LOGIN PASSWORD '$ROLE_PASSWORD';
11        CREATE SCHEMA ${each.key} AUTHORIZATION ${each.key};
12        REVOKE ALL ON SCHEMA ${each.key} FROM PUBLIC;
13        CREATE TABLE ${each.key}.states (id bigint NOT NULL DEFAULT nextval('public.global_states') PRIMARY KEY, name text, data text);
14        CREATE UNIQUE INDEX states_by_name ON ${each.key}.states (name);
15        ALTER TABLE ${each.key}.states OWNER TO ${each.key};"
16    EOT
17
18    environment = {
19      ADMIN_PASSWORD = random_password.admin.result
20      ROLE_PASSWORD  = random_password.role[each.key].result
21    }
22  }
23}

The passwords are generated, and the bootstrap directory hands back one connection string for each directory:

HCL
1output "connection_strings" {
2  description = "One connection string for each directory. Each role can reach only its own schema."
3  sensitive   = true
4  value = {
5    for d in local.directories :
6    d => "postgres://${d}:${random_password.role[d].result}@localhost:5544/terraform_state?sslmode=disable"
7  }
8}

You can download the files: bootstrap/main.tf, platform/main.tf and environments/dev/main.tf. The UAT and prod files differ from dev only in the schema name and the values from Part 5.

The plan was 14 to add. Then I asked PostgreSQL what it had made:

CODE
1  Schema  |  Name  | Type  |  Owner
2----------+--------+-------+----------
3 dev      | states | table | dev
4 platform | states | table | platform
5 prod     | states | table | prod
6 uat      | states | table | uat

The starting point: Part 5's environments, with local state

I recreated Part 5's setup at version 1.2.0 with ordinary local state: the platform (1 resource) and dev, UAT and prod (11 resources each). Each directory had a terraform.tfstate file, about 12 KB for the platform and about 29 KB for each environment:

CODE
112233  platform/terraform.tfstate
228842  environments/dev/terraform.tfstate
328842  environments/uat/terraform.tfstate
428862  environments/prod/terraform.tfstate

The backend block

In each directory I added a backend block to the terraform block. This is dev's:

HCL
1terraform {
2  backend "pg" {
3    schema_name          = "dev"
4    skip_schema_creation = true
5    skip_table_creation  = true
6    skip_index_creation  = true
7  }

Notice what is missing: the connection string. A backend block cannot use variables, and a password should not live in a file anyway. The backend reads the connection string from an environment variable, PG_CONN_STR. I set it for each directory from the bootstrap output, and each directory gets its own role's string:

CODE
1export PG_CONN_STR="$(terraform -chdir=../../bootstrap output -json connection_strings \
2  | python3 -c 'import sys,json; print(json.load(sys.stdin)["dev"])')"

Migrate the state

PROMPT
1terraform init -migrate-state

Terraform noticed the existing local state and asked what to do:

CODE
1Initializing the backend...
2Do you want to copy existing state to the new backend?
3  Pre-existing state was found while migrating the previous "local" backend to the
4  newly configured "pg" backend. No existing state was found in the newly
5  configured "pg" backend. Do you want to copy this state to the new "pg"
6  backend? Enter "yes" to copy and "no" to start with an empty state.
7
8  Enter a value: yes
9
10Successfully configured the backend "pg"! Terraform will automatically
11use this backend unless the backend configuration changes.

I answered yes in dev. For the other three I used -force-copy, which answers it for me. Then I checked three things.

The local files are empty. Terraform left the files in place, but emptied them: all four were 0 bytes.

A plan still sees everything. In each directory:

CODE
1platform: No changes. Your infrastructure matches the configuration.
2dev:      No changes. Your infrastructure matches the configuration.
3uat:      No changes. Your infrastructure matches the configuration.
4prod:     No changes. Your infrastructure matches the configuration.

The state is in the database. I asked PostgreSQL, as its administrator, what was in each schema:

CODE
1dev      | default | 28841 | t
2platform | default | 12233 | f
3prod     | default | 28861 | t
4uat      | default | 28841 | t

The columns are the directory, the Terraform workspace (default, because I did not use workspaces), the size in bytes, and whether the state contains a field called result. That is where the random provider stores a generated password. Dev, UAT and prod contain one. The platform does not.

Docker Desktop with everything running: the cluster node, the three environment databases and tfstate-db, the new state store, on port 5544

Docker Desktop with everything running: the cluster node, the three environment databases and tfstate-db, the new state store, on port 5544

Locking: two commands at once

A lock stops two commands from changing the same state at the same moment. I tested it in dev. In one terminal I started an apply that replaces the database container. That takes about ten seconds, because Terraform waits for SQL Server to be healthy. Three seconds in, I ran a plan in a second terminal:

CODE
1Error: Error acquiring the state lock
2
3Error message: Workspace is already locked: default
4Lock Info:
5  ID:        ffdc3bb9-c4cf-0bb3-d896-fb96dc27336c
6  Operation: OperationTypePlan
7  Who:       <user>@<laptop>
8  Version:   1.17.2
9
10Terraform acquires a state lock to protect the state from being written
11by multiple users at the same time. Please resolve the issue above and try
12again.

The second command was refused at once. Look closely at the "Lock Info". It describes my second command, a plan, not the apply that holds the lock. With this backend it does not tell me who holds the lock. Other backends may record the holder, and I did not test them.

I ran a third command, with -lock-timeout=60s. It printed Acquiring state lock. This may take a few moments..., waited for the apply to finish, and then ran: No changes.

One state, one lock. The second command is refused at once, and the third waits for its turnScroll sideways, or tap the diagram to open it full size

One state, one lock. The second command is refused at once, and the third waits for its turn

Access: each directory has its own key

The roles make the isolation real. I tried dev's credentials against prod's directory:

CODE
1$ cd environments/prod
2$ PG_CONN_STR=<dev's connection string> terraform plan
3Error: pq: permission denied for schema prod

And prod's own credentials in the same directory:

CODE
1No changes. Your infrastructure matches the configuration.

In Part 5, separate directories meant a command in dev could not change prod by accident. Now someone holding only dev's credentials cannot read prod's state at all.

A crash: kill the apply

What happens to the lock if a run dies? I started the same apply again, waited four seconds, and killed Terraform with kill -9, so it had no chance to clean up.

The lock was not left behind. A plan straight afterwards ran without waiting. This backend ties the lock to the database connection, so when the process died, the connection closed and the lock went with it. In a backend where the lock is a stored record, a crash can leave it behind, and terraform force-unlock removes it. I did not need it here.

But the infrastructure was left half-changed. The plan showed:

CODE
1# module.shop.docker_container.db has been deleted
2# module.shop.docker_container.db will be created
3# module.shop.terraform_data.db_schema must be replaced
4
5Plan: 2 to add, 0 to change, 1 to destroy.

I ran the apply to repair it, and it failed:

CODE
1Error: Unable to create container: Error response from daemon: Conflict. The
2container name "/dev-db" is already in use by container "<id>". You have to
3remove (or rename) that container to be able to reuse that name.

The killed run had already asked Docker to create the new database container. It existed, healthy, but Terraform's state did not record it. I removed the orphan with docker rm -f dev-db, applied again, and the result was Apply complete! Resources: 2 added, 0 changed, 0 destroyed. A plan said No changes, and the site answered on its port.

A lock is not a transaction. It stops two commands clashing, and it does not make one command all-or-nothing. A killed apply can leave real resources that the state does not know about, and the fix is to find them and clean up.

A teammate: a fresh clone

I committed the backend blocks and the bootstrap directory to the repository, and then I made a fresh clone in another folder, as a teammate would. It had no state files, because they are not in git. There was one catch: the cluster's connection file, platform/kubeconfig, is a credential and is not in git either, so I copied it in, as a teammate would get it from me. Then in the clone's dev directory, with dev's connection string:

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

The clone saw exactly what I saw, with zero local state files. That is what "shared" means.

Clean up

I destroyed the directories through the remote backend, then the state store itself:

CODE
1prod: Destroy complete! Resources: 11 destroyed.
2uat: Destroy complete! Resources: 11 destroyed.
3dev: Destroy complete! Resources: 11 destroyed.
4platform: Destroy complete! Resources: 1 destroyed.
5bootstrap: Destroy complete! Resources: 14 destroyed.

The order matters: the state store is last, because the other four need it to run. Docker's kind network was left behind again, as in Parts 4 and 5, so I removed it by hand.

After everything was destroyed, Docker Desktop had no containers left

After everything was destroyed, Docker Desktop had no containers left

What remote state gave me

What I wantedWhat happened
State that is not on one laptopA teammate's fresh clone read it with no local files
Two commands must not collideThe second was refused at once, and a timeout made the third wait
Each environment keeps its own stateSeparate schemas, so a plan in one directory saw only its own
Dev cannot reach prod's stateDev's credentials got permission denied for schema prod
A crash must not jam the stateThe lock released itself, and the half-made container was my cleanup
No change to the resourcesEvery plan said No changes after the migration

Where this falls short

  • One PostgreSQL container on a laptop. It has no replication and no backups. A real state store needs both. Cloud storage services typically offer both, and often keep old versions of the state as well. This backend keeps one copy of each state, and I did not test restoring an old one.
  • The lock information. With this backend it described my own command, not the holder. A cloud backend may do better, and I did not test one.
  • Connection strings in environment variables. They keep passwords out of the files, but they are still in my shell. A real setup would get them from a secret manager or a login, per person.
  • The bootstrap directory's state is a local file. That one file is the keys to the rest.
  • The pg backend is not the common choice. Most teams use S3, Azure Blob Storage or Google Cloud Storage. The ideas are the same, and the configuration is different.
  • The kubeconfig is shared by hand. In Part 5 the environments read the cluster's connection file from the platform directory. A teammate has to get that file separately. A real setup would let each person log in to the cluster. Part 7 removes the file by reading the cluster's details from the platform's state.
  • No pipeline. I still ran every command myself. Part 5 describes where a pipeline fits, and a pipeline needs exactly this: a shared, locked state and a credential for each environment. Part 7 builds one.
  • Parallel provisioners. My bootstrap hit races between local provisioners, and I fixed them by adding ordering. The point holds for any resource that runs commands against one shared object.

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.