The Wrong-Workspace Trap
The wrong-workspace trap is an apply that runs in the wrong workspace and changes the wrong environment. The configuration is the same, so nothing looks wrong until the damage is done.
Check the workspace first
Never apply without knowing which workspace is current.
terraform workspace show
terraform planGuard prod with a precondition
The run stops unless confirm_prod is true.
lifecycle {
precondition {
condition = terraform.workspace != "prod" || var.confirm_prod
error_message = "Refusing to run in the prod workspace without confirm_prod set to true."
}
}The guard in action
This apply in prod stops before it writes anything. The error names the failed condition.
terraform workspace select prod
terraform apply -auto-approveExample
# main.tf
terraform {
required_providers {
local = {
source = "hashicorp/local"
version = "~> 2.0"
}
}
}
variable "confirm_prod" {
type = bool
default = false
}
resource "local_file" "guarded" {
content = "Safe to write in ${terraform.workspace}."
filename = "${path.module}/guarded-${terraform.workspace}.txt"
lifecycle {
precondition {
condition = terraform.workspace != "prod" || var.confirm_prod
error_message = "Refusing to run in the prod workspace without confirm_prod set to true."
}
}
}
# commands
terraform init
terraform workspace new dev
terraform apply -auto-approve
terraform workspace new prod
terraform apply -auto-approve
terraform apply -var="confirm_prod=true" -auto-approveKey points
- Workspaces share credentials and the backend. Only the state file differs.
- terraform workspace show is the check before an apply. It takes one second.
- A guard can refuse prod unless a variable confirms it. The run stops before it writes anything.
- A precondition on a resource makes the guard. Terraform checks it during the plan.
- Destroy in the wrong workspace is the worst case. It removes the wrong environment.
The apply in dev works, because the guard only blocks prod. The first apply in prod stops with an error, because confirm_prod is still false. The second prod apply passes the flag, so the guard lets it through. The guard turns a silent mistake into a loud stop.
Note
print the workspace in the plan step. A habit beats a rescue.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
What is the simplest guard against applying in the wrong workspace?