Opscraft
Terraform · Lesson 7 of 12 · 3 min read

Structuring environments and repositories

Workspaces vs separate directories

Workspaces (terraform workspace new staging) keep multiple state files for one configuration (terraform.workspace can drive differences). Simple, but:

  • all environments share the same code version — you can't test a change in dev while prod stays on the old code without branches;
  • easy to apply to the wrong workspace;
  • same backend/credentials for all — weak isolation between prod and non-prod.

Most teams prefer separate directories (or stacks) per environment calling shared, versioned modules:

Enlarge diagramWorkspacesSeparate directoriesOne code folder, one state per workspaceEvery env always runs the same codeEasy to apply to the wrong workspaceSame backend and credentials for allenvs/dev, envs/prod, each with own statePin module versions per envSeparate credentials per accountMore files, clearer blast radius
Figure 1. Two ways to run several environments. Most teams choose separate directories calling versioned modules.
Swipe sideways to see all of it, or tap to open it full screen.
infra/
├── modules/                    # or a separate versioned modules repo
├── live/
│   ├── dev/
│   │   ├── network/   (backend key dev/network)
│   │   ├── eks/       (backend key dev/eks)
│   │   └── apps-iam/
│   ├── staging/...
│   └── prod/
│       ├── network/
│       ├── eks/
│       └── data/      (RDS etc.)

Each environment can live in its own AWS account with its own state bucket and deploy role — strong isolation and small blast radius.

Splitting state into stacks

One huge state for everything means slow plans, frequent lock contention, and a large blast radius (a mistake can touch everything). Split by layer and change frequency: network (rarely changes) → cluster → shared services → apps. Connect stacks via:

Enlarge diagramappsIRSA roles, queues, buckets per service: changes dailyshared servicesECR, DNS zones, ingressclusterEKS, node groups, add-onsnetworkVPC, subnets, NAT: changes rarely
Figure 2. Split one huge state into layers. Lower layers change rarely; upper layers read their outputs.
Swipe sideways to see all of it, or tap to open it full screen.
  • terraform_remote_state data source (read another stack's outputs — requires read access to its state),
  • or publishing outputs to SSM Parameter Store and reading them with data sources (looser coupling, no state access needed),
  • or data source lookups by tags/names.

Terragrunt

Terragrunt is a thin wrapper that keeps large multi-environment setups DRY: generates backend and provider config per directory, passes inputs, handles dependencies between stacks (dependency blocks), and runs commands across many stacks (terragrunt run-all plan). Common in organisations with dozens of accounts.