Cheat notes · Module 05 · State, modules and environments
Dev and prod without copy and paste
A five-minute review for when you have done this module and want it back in your head. Open the full module for the steps and the lab, or the full text to print.
The idea
Dev and prod are two directories with the same module and different wiring: their own state key, target and inputs, reviewed as files. A workspace is only a second state for the same files, invisible in a pull request.
Remember
- Environment directory:
backend.tf(which state),providers.tf(which target),terraform.tfvarsandmain.tf(which numbers). No logic. - Blast radius: one state. Dev's lock does not block prod, and a mistake in dev cannot touch prod.
- Promotion: one merge, then an apply in dev, then in prod.
- Workspace:
env:/prod/dev/terraform.tfstatein the same bucket, same credentials, same commit. - CODEOWNERS names who reviews
modules/,envs/prod/,state/and.github/.
Pitfalls
- Copying dev's
backend.tfinto prod: prod's code runs against dev's state and plans to destroy dev.grep -n key envs/*/backend.tf. - A workspace per environment: nobody can see in the pull request which one a change will hit.
Commands
terraform workspace list | Named states for this directory |
terraform init -reconfigure | Use the backend in backend.tf, copy nothing |
kubectl get namespaces -l environment=prod | What prod manages |
envs/prod/main.tf (module 05)
module "checkout" {
source = "../../modules/team-namespace"
team = "checkout"
environment = var.environment
quota = { pods = 30, cpu = "8", memory = "16Gi" }
}
Test yourself
Answer in your head first, then open the answer.
What does terraform workspace new prod create?
A second, empty state for the same code in the same backend.
You apply a module change in dev only. What does prod's plan show?
The same change, waiting for prod's apply.
Which line differs between dev's and prod's backend.tf?
The key.
Where module 05 leaves you: envs/prod manages checkout-prod and catalog-prod (seven objects each) from the same module, with its state in prod/terraform.tfstate and its own lock. .github/CODEOWNERS names who reviews modules/, envs/prod/, state/ and .github/. Only the default workspace exists.