Interview › Infrastructure as Code (Terraform, Ansible)
How do you structure Terraform code for multiple environments (dev/staging/prod)?
Infrastructure as Code (Terraform, Ansible) · Basic level
Answer
I structure multi-environment Terraform with reusable modules plus thin environment root modules. Each environment has its own backend key or backend configuration, variable values, plan pipeline, and approval rules. Shared logic belongs in modules; environment-specific sizing, account IDs, regions, and feature flags belong in env roots or tfvars.
Technical explanation
Keep global/shared resources separate from app-specific resources when their lifecycles differ.
Avoid one giant state file; use meaningful boundaries such as network, cluster, data, and service.
Each environment should be independently plannable and recoverable.
Keep Terraform's ownership boundary clear: one state should own a resource or field, and other tools should consume published outputs instead of modifying it.
Use fmt, validate, linting, policy checks, plan review, and state locking before production applies.
Design for small blast radius by splitting state around lifecycle, permissions, and recovery boundaries.
Hands-on example
1. Create environment separation for: How do you structure Terraform code for multiple environments (dev/staging/prod)?
2. Use reusable modules with separate root modules:
infra/
modules/vpc/
envs/dev/main.tf
envs/stage/main.tf
envs/prod/main.tf
3. Give each environment a separate backend key and credentials boundary:
terraform { backend "s3" { key = "envs/prod/network.tfstate" bucket = "company-tfstate-prod" region = "ap-south-1" use_lockfile = true } }4. Run PR plans for all environments but require manual approval and stricter policy for prod.
5. Use workspaces only for low-risk ephemeral variants after documenting their limitations.
Check how well your resume matches the role with our free resume checker— match score, ATS check, and the skills you're missing.
More Infrastructure as Code (Terraform, Ansible) interview questions
- What is the difference between using workspaces and separate state files per environment?
- What is the purpose of terraform plan -out and applying a saved plan?
- What are Terraform workspaces, and what are their limitations for environments?
- What does terraform refresh do, and how has its behaviour changed?
- How do you handle resources changed manually outside Terraform?
- What are provisioners, and why are they considered a last resort?
- What is configuration drift, and how does Terraform detect it?
- What is the difference between local-exec and remote-exec provisioners?