Someone ran `terraform apply` with dev variables against the prod state. How do you make that impossible?
BeginnerScenarioMulti-env and multi-account
Answer
Situation read → Humans running Terraform locally with broad credentials will eventually hit the wrong environment. Remove the possibility, don't rely on care.
What I'd do →
- Separate state and backend per environment (separate directories or accounts), not a variable switch.
- Separate AWS accounts with separate roles; a dev role simply has no rights in prod.
- Assert the account inside Terraform so a mismatch fails at plan:
provider "aws" {
region = "ap-south-1"
allowed_account_ids = ["444455556666"] # prod
}
- Prod applies only from CI after a reviewed plan; humans get read-only in prod.
- Recover from this one: check the plan or apply output, reconcile with a fresh plan, and restore the previous state version from S3 versioning if state was damaged.
Why → allowed_account_ids turns "wrong credentials" into an immediate error instead of a change.
Interview tip → Mention allowed_account_ids; few candidates know it exists.
More on Multi-env and multi-account
Design the AWS account structure for a 50-engineer startup that's growing fast.IntermediateHow do you promote the same build from dev to staging to prod?BeginnerBugs keep passing staging and appearing in production. How do you make staging closer to prod?IntermediateHow do you structure Terraform for dev, staging and prod? Workspaces, directories or Terragrunt?IntermediateDevelopers want a preview environment for every pull request. How would you build it?AdvancedHelm values files or Kustomize overlays for per-environment config?Beginner