Interview Prep/Terraform/State Backends and Workspaces

You have dev, stage and prod backends that differ only by bucket and key. How do you avoid copy-pasting `backend.tf`?

IntermediateScenarioState Backends and Workspaces
Answer

Situation read → Backend blocks can't use variables.

What I'd do → Use partial configuration: leave the backend block mostly empty and pass the rest at init.

terraform {
  backend "s3" {}
}
terraform init -reconfigure -backend-config=envs/prod.backend.hcl
# envs/prod.backend.hcl
bucket = "acme-tfstate-prod"
key    = "app/terraform.tfstate"
region = "ap-south-1"

Why → One code path, per-environment backend config files that are easy to review.

Interview tip → Use -reconfigure when switching between environments locally, and watch for the wrong-file mistake.

All Terraform questions Roadmap: Terraform in production

More on State Backends and Workspaces