Module 6: Terraform State Management

Lab 6A: Remote Backend, Migration, Locking, Workspaces, and Remote State

Goal
Start with local state, migrate it into a PostgreSQL backend using partial configuration, trigger a lock conflict, create a second workspace, and read outputs from another configuration.
Time
30 min
Cost
$0
Prerequisites
Docker running
Objectives
0 of 7 checked

Setup: start a PostgreSQL container

Shell
docker run -d --name tf-pg \
  -e POSTGRES_USER=tf -e POSTGRES_PASSWORD=tfpass -e POSTGRES_DB=tfstate \
  -p 5432:5432 postgres:16
export PG_CONN_STR="postgres://tf:tfpass@localhost:5432/tfstate?sslmode=disable"

The pg backend reads PG_CONN_STR, so the connection string never appears in code. These are lab-only credentials.

Starting files

Create ~/tf-course/lab6a/producer/main.tf:

~/tf-course/lab6a/producer/main.tfHCL
terraform {
  required_version = "~> 1.12.0"

  required_providers {
    random = {
      source  = "hashicorp/random"
      version = "~> 3.7"
    }
    local = {
      source  = "hashicorp/local"
      version = "~> 2.5"
    }
  }
}

resource "random_pet" "app" {
  length = 2
}

resource "local_file" "marker" {
  filename = "${path.module}/marker-${terraform.workspace}.txt"
  content  = "app = ${random_pet.app.id}\nworkspace = ${terraform.workspace}\n"
}

output "app_name" {
  value = random_pet.app.id
}

Steps

Shell
cd ~/tf-course/lab6a/producer
terraform init && terraform apply -auto-approve
ls terraform.tfstate*

Expected output: terraform.tfstate. Run terraform apply -auto-approve once more, then check ls again. A .backup file appears once state has been rewritten. Note the app_name output.

Insert this inside the existing terraform {} block:

HCL
  backend "pg" {}

Every setting comes from the environment, through PG_CONN_STR. Then run:

Shell
terraform plan

Expected output: an error that the backend configuration changed and initialization is required.

Shell
terraform init -migrate-state

Expected output: a prompt asking whether to copy existing state from local to the pg backend. Type yes. You should then see Successfully configured the backend "pg"!

Shell
terraform state list
docker exec tf-pg psql -U tf -d tfstate -c "select name from terraform_remote_state.states;"

Expected output: both resources are listed, and the table has one row, default. Run terraform plan, and it should report No changes, with the same pet name. Delete the stale local copies with rm -f terraform.tfstate terraform.tfstate.backup, then run terraform plan again. It still reports no changes, because the authoritative copy is in PostgreSQL.

In terminal 1 (also run export PG_CONN_STR=... there), start an apply and leave it waiting at the prompt:

Shell
terraform apply

Terraform holds the lock while it waits for your answer.

In terminal 2:

Shell
terraform plan

Expected output: Error acquiring the state lock, with the lock ID, operation, and holder.

Still in terminal 2, wait for the lock instead:

Shell
terraform plan -lock-timeout=60s

Then answer no in terminal 1. Terminal 2's plan proceeds as soon as the lock is released.

Shell
terraform workspace new staging
terraform apply -auto-approve
terraform workspace list
docker exec tf-pg psql -U tf -d tfstate -c "select name from terraform_remote_state.states;"

Expected output:

  • The apply creates 2 new resources, a different pet name, and marker-staging.txt.
  • workspace list shows default and * staging.
  • The table now has two rows.

Run terraform workspace delete default. Expected output: an error, because the default workspace can't be deleted. Then switch back with terraform workspace select default.

Create ~/tf-course/lab6a/consumer/main.tf:

~/tf-course/lab6a/consumer/main.tfHCL
terraform {
  required_version = "~> 1.12.0"
}

data "terraform_remote_state" "producer" {
  backend   = "pg"
  workspace = "staging"
  config    = {} # pg reads PG_CONN_STR from the environment
}

output "producer_app" {
  value = data.terraform_remote_state.producer.outputs.app_name
}
Shell
cd ../consumer
terraform init && terraform apply -auto-approve

Expected output: producer_app equals the staging pet name. Notice that the consumer needed full read access to the producer's state, which is why HashiCorp recommends narrower alternatives where possible.

Cleanup

Shell
cd ../consumer && terraform destroy -auto-approve
cd ../producer
terraform workspace select staging && terraform destroy -auto-approve
terraform workspace select default && terraform workspace delete staging
terraform destroy -auto-approve
docker rm -f tf-pg && unset PG_CONN_STR

Lab 6A complete. Every step is checked.

This lab has no verification checklist in the course file, so it counts as complete when every step is checked.