Skip to main content

Organizing Terraform Environments at Scale

Compare Terraform workspaces, directory-per-environment layouts and Terragrunt, and pick the structure that keeps dev, staging and prod safely apart.

26 Terms

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 .tfvars files 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.

flowchart TD A{How many environments
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.

Bash
terraform workspace list
terraform workspace new staging
terraform workspace new prod
terraform workspace show
# prod
terraform workspace select staging
HCL
# The active workspace name is available as terraform.workspace
resource "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.

TEXT
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 code
Common Mistake

Branching 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.

Bash
infrastructure/
ā”œā”€ā”€ modules/
│ ā”œā”€ā”€ vpc/
│ ā”œā”€ā”€ ecs-service/
│ └── rds-postgres/
└── environments/
ā”œā”€ā”€ dev/
│ ā”œā”€ā”€ main.tf
│ ā”œā”€ā”€ backend.tf
│ ā”œā”€ā”€ variables.tf
│ └── terraform.tfvars
ā”œā”€ā”€ staging/
│ └── (same files)
└── prod/
└── (same files)
HCL
# environments/prod/backend.tf
terraform {
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"
}
}
}
HCL
# environments/prod/main.tf
provider "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.

Tip

Pin modules with ?ref=v2.4.0. Dev can try v2.5.0 first, 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.

HCL
# environments/dev/terraform.tfvars
region = "ap-south-1"
vpc_cidr = "10.10.0.0/16"
instance_count = 1
cpu = 256
HCL
# environments/prod/terraform.tfvars
region = "ap-south-1"
vpc_cidr = "10.0.0.0/16"
instance_count = 4
cpu = 1024
Bash
cd environments/prod
# Save the plan, review it, then apply exactly that plan
terraform init
terraform plan -out=prod.tfplan
terraform show prod.tfplan
terraform apply prod.tfplan

Applying 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.

ā—ˆ DIAGRAM
live/
ā”œā”€ā”€ root.hcl
ā”œā”€ā”€ dev/
│ ā”œā”€ā”€ vpc/terragrunt.hcl
│ └── ecs-service/terragrunt.hcl
└── prod/
ā”œā”€ā”€ vpc/terragrunt.hcl
└── ecs-service/terragrunt.hcl
HCL
# live/root.hcl : the backend is defined once
remote_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
}
}
HCL
# live/prod/ecs-service/terragrunt.hcl
include "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"
}
Bash
cd live/prod/ecs-service
terragrunt plan
terragrunt apply

Each 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.

HCL
# 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
}
Bash
# Apply every component under prod in dependency order
cd live/prod
terragrunt run --all apply

Terragrunt'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 apply applies 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

  1. Isolate production by account. A separate AWS account and IAM role per environment is a stronger boundary than any folder or workspace.
  2. Make the target obvious. Show the current directory or workspace in your shell prompt and in CI job names.
  3. Prefer data over branching. Differences belong in .tfvars, not in terraform.workspace conditionals.
  4. Version your modules. Pin each environment to a git tag and promote versions dev, staging, prod.
  5. Save and review plans. Use plan -out and apply the saved file.
  6. 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.
  7. Never share state buckets across trust levels. Anyone who can write a state file can change what Terraform believes is deployed.
Remember

A 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

Resources

Explore More in Terraform Modules and Code Organisation

All 3 Topics

Frequently Asked Questions

Is Organizing Terraform Environments at Scale free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Organizing Terraform Environments at Scale topic cover?

Compare Terraform workspaces, directory-per-environment layouts and Terragrunt, and pick the structure that keeps dev, staging and prod safely apart.

Found a mistake, an outdated step or a broken link?