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 Infrastructure as Code, and what problems does it solve over click-ops?
- What is the difference between declarative and imperative IaC, and where do Terraform and Ansible fall?
- What is the difference between configuration management and provisioning?
- What is Terraform, and what is the core plan/apply workflow?
- What does terraform init do?
- What is the Terraform state file, and why is it critical?
- Why should state be stored remotely, and what backend would you use on AWS?
- What is state locking, and why does it matter for teams?