Overview and What You Will Learn
To keep dev, staging and production apart in Terraform, give each environment its own state file, its own credentials and its own working directory. Terraform workspaces only give you separate state files inside one backend, so they are a convenience, not a safety boundary. A directory-per-environment layout is the safest default, and Terragrunt removes the repeated backend and dependency boilerplate once you have many environments.
In this lab you will:
- See exactly what a workspace separates and what it does not
- Build a directory-per-environment layout with a separate backend per environment
- Keep environment values in
.tfvarsfiles and pin shared module versions - Choose between a mono-repo and multiple repos
- Remove duplicated backend code and manage module dependencies with Terragrunt
- Decide which approach fits your team
Why This Matters in Production
The failure that drives most restructuring is simple: an engineer runs terraform apply believing they are in staging while the shell is pointed at production. When the environment is just a name stored in a hidden file (.terraform/environment), nothing in the command makes the target obvious. Platform teams at companies like Shopify or Atlassian avoid the whole class of mistakes by making the environment a physical folder plus a separate cloud account, so reaching production requires a deliberate cd and different credentials.
Core Principles
Isolation has three independent layers: state (which resources Terraform believes it owns), credentials (what the run is allowed to change) and code (which configuration is applied). Good structure separates all three, and workspaces separate only the first.
and teams?} -->|2 to 3, one team| B[Directory per environment] A -->|Many, deep dependencies| C[Terragrunt on top] A -->|Throwaway or per-branch copies| D[Workspaces] B --> E([Separate state, account
and credentials]) C --> E D --> F([Same backend and credentials]) classDef pick fill:#DBEAFE,color:#1E293B classDef good fill:#10B981,color:#FFFFFF classDef warn fill:#F97316,color:#FFFFFF class A,B,C,D pick class E good class F warn
| Approach | What it separates |
|---|---|
| Workspaces | State file only |
| Directory per environment | State, code and (with roles) credentials |
| Terragrunt | Same as directories, with less duplication |
Workspaces fit short-lived copies of identical infrastructure, such as a per-pull-request test stack. HashiCorp's own guidance is that workspaces are not suitable for strong isolation between deployments that need different credentials, which is what dev versus production usually is.
Detailed Step-by-Step Practical Lab
Milestone 1: See What a Workspace Really Is
A workspace is a named state file inside the same backend, selected by a local setting. It does not change your AWS account, credentials, variables or backend bucket.
terraform workspace list terraform workspace new stagingterraform workspace new prod terraform workspace show# prod terraform workspace select staging# The active workspace name is available as terraform.workspaceresource "aws_instance" "app" { ami = var.ami_id instance_type = terraform.workspace == "prod" ? "t3.large" : "t3.micro"}With an S3 backend, each non-default workspace stores its state under an env:/<workspace>/ prefix in the same bucket, so anyone who can write to the bucket can modify every workspace.
What workspaces separate: What they do NOT separate:* The state file * AWS account and credentials* Resources tracked in it * Backend bucket and region * Variable files and codeCommon MistakeBranching on
terraform.workspace == "prod"all over the code. Configuration then differs by a hidden setting that is not visible in a diff or a pull request. Put differences in variables instead.
Milestone 2: Build a Directory-Per-Environment Layout
Each environment is its own Terraform root module with its own backend. Shared logic lives in modules/ and is consumed by every environment.
infrastructure/āāā modules/ā āāā vpc/ā āāā ecs-service/ā āāā rds-postgres/āāā environments/ āāā dev/ ā āāā main.tf ā āāā backend.tf ā āāā variables.tf ā āāā terraform.tfvars āāā staging/ ā āāā (same files) āāā prod/ āāā (same files)# environments/prod/backend.tfterraform { backend "s3" { bucket = "razorpay-tfstate-prod" key = "orders-api/terraform.tfstate" region = "ap-south-1" encrypt = true use_lockfile = true # native S3 locking, Terraform 1.10 and later assume_role = { role_arn = "arn:aws:iam::123456789012:role/terraform-prod" } }}# environments/prod/main.tfprovider "aws" { region = var.region assume_role { role_arn = "arn:aws:iam::123456789012:role/terraform-prod" }} module "vpc" { source = "git::https://github.com/razorpay/tf-modules.git//vpc?ref=v2.4.0" cidr = var.vpc_cidr} module "orders_api" { source = "git::https://github.com/razorpay/tf-modules.git//ecs-service?ref=v2.4.0" vpc_id = module.vpc.vpc_id subnet_ids = module.vpc.private_subnet_ids desired_count = var.instance_count cpu = var.cpu}Use one state bucket and one IAM role per environment, ideally in a separate AWS account. For older Terraform versions that lack use_lockfile, use a DynamoDB lock table instead.
TipPin modules with
?ref=v2.4.0. Dev can tryv2.5.0first, and prod moves to it only after dev and staging have applied cleanly.
Milestone 3: Keep Environment Values in tfvars
Differences between environments should be data, not code. Terraform automatically loads a file named exactly terraform.tfvars or any *.auto.tfvars in the working directory, so -var-file is only needed for files with other names.
# environments/dev/terraform.tfvarsregion = "ap-south-1"vpc_cidr = "10.10.0.0/16"instance_count = 1cpu = 256# environments/prod/terraform.tfvarsregion = "ap-south-1"vpc_cidr = "10.0.0.0/16"instance_count = 4cpu = 1024cd environments/prod # Save the plan, review it, then apply exactly that planterraform initterraform plan -out=prod.tfplanterraform show prod.tfplanterraform apply prod.tfplanApplying a saved plan guarantees that what you reviewed is what runs, which matters most for production.
Milestone 4: Choose Mono-Repo or Multi-Repo
Start with one repository. Split only when a different team needs to own a layer with different access rules.
| Option | Choose it when |
|---|---|
| Mono-repo | One platform team owns everything, you want atomic changes across layers |
| Multi-repo | Separate teams own networking, data and apps with different permissions |
A multi-repo setup adds real costs: cross-repo module versioning, separate pipelines and separate access requests. A repository that merely feels large is not a reason to split.
Whichever you choose, run plan automatically on pull requests and require approval before apply on production. Per-environment CI jobs use that environment's role, so a developer laptop never needs production write access.
Milestone 5: Remove Backend Duplication with Terragrunt
In a directory-per-environment layout, every backend.tf is nearly identical. Terragrunt lets you define the backend once and generate it for each folder. A common layout puts a root config file at the top and one folder per environment and component.
live/āāā root.hclāāā dev/ā āāā vpc/terragrunt.hclā āāā ecs-service/terragrunt.hclāāā prod/ āāā vpc/terragrunt.hcl āāā ecs-service/terragrunt.hcl# live/root.hcl : the backend is defined onceremote_state { backend = "s3" generate = { path = "backend.tf" if_exists = "overwrite_terragrunt" } config = { bucket = "razorpay-tfstate" key = "${path_relative_to_include()}/terraform.tfstate" region = "ap-south-1" encrypt = true use_lockfile = true }}# live/prod/ecs-service/terragrunt.hclinclude "root" { path = find_in_parent_folders("root.hcl")} terraform { source = "git::https://github.com/razorpay/tf-modules.git//ecs-service?ref=v2.4.0"} inputs = { service_name = "orders-api" cpu = 1024 desired_count = 4 environment = "prod"}cd live/prod/ecs-serviceterragrunt planterragrunt applyEach folder gets its own state key automatically, such as prod/ecs-service/terraform.tfstate.
Milestone 6: Manage Dependencies Between Modules
A dependency block lets one component read another component's outputs and tells Terragrunt the correct apply order.
# live/prod/ecs-service/terragrunt.hcl (additional blocks)dependency "vpc" { config_path = "../vpc" # Lets plan and validate work before the VPC has ever been applied mock_outputs = { vpc_id = "vpc-00000000" private_subnet_ids = ["subnet-00000000"] } mock_outputs_allowed_terraform_commands = ["init", "validate", "plan"]} inputs = { vpc_id = dependency.vpc.outputs.vpc_id subnet_ids = dependency.vpc.outputs.private_subnet_ids}# Apply every component under prod in dependency ordercd live/prodterragrunt run --all applyTerragrunt's command line has been reorganized in recent releases. Older versions use terragrunt run-all apply and terragrunt graph-dependencies, newer ones use terragrunt run --all apply and terragrunt dag graph. Run terragrunt --help to see which form your installed version expects.
Security
run --all applyapplies many components without a per-component review. Use it freely in dev, but in production review a combined plan first and keep an approval step in CI.
Production Best Practices & Common Pitfalls
- Isolate production by account. A separate AWS account and IAM role per environment is a stronger boundary than any folder or workspace.
- Make the target obvious. Show the current directory or workspace in your shell prompt and in CI job names.
- Prefer data over branching. Differences belong in
.tfvars, not interraform.workspaceconditionals. - Version your modules. Pin each environment to a git tag and promote versions dev, staging, prod.
- Save and review plans. Use
plan -outand apply the saved file. - Adopt Terragrunt for a reason. It pays off with many environments or long dependency chains, and adds a tool and DSL to learn for small setups.
- Never share state buckets across trust levels. Anyone who can write a state file can change what Terraform believes is deployed.
RememberA workspace is a label on a state file. It is not an environment, an account or an access control.
Quick Reference & Troubleshooting Commands
| Approach | Best for |
|---|---|
| Workspaces | Temporary copies of the same stack |
| Directory per environment | Most teams, clearest mental model |
| Terragrunt | Many environments, deep dependencies |
| Command | Description |
|---|---|
terraform workspace show |
Print the active workspace |
terraform workspace select NAME |
Switch workspace |
terraform plan -out=FILE |
Save a plan for review |
terraform state list |
List resources in the current state |
terragrunt run --all plan |
Plan every component below this folder |
| Symptom | Likely cause and fix |
|---|---|
| Applied to the wrong environment | Hidden workspace or wrong folder, use directories plus per-environment roles |
Error acquiring the state lock |
Another run holds the lock, wait or investigate before force-unlocking |
| Dependency outputs are empty | Dependency not applied yet, apply it first or add mock_outputs for plan |
| Backend config drifts between folders | Hand-edited backend.tf, generate it from the root Terragrunt config |
| Terragrunt and Terraform version errors | Incompatible versions, check Terragrunt's supported Terraform versions |