Andrew Mercer
on this page

The goal of every multi-environment setup is the same:

  1. Same code. Dev, test and prod run the same modules at (eventually) the same versions.
  2. Different inputs. Every intentional difference is a reviewable value in one place.
  3. Separate state. One environment's apply can't touch another's state.
  4. Separate credentials. The dev pipeline physically can't change prod.

The approaches below differ in how they get there. For the full architectural picture (layers, repos, promotion diagrams) see the architecture guide.

Approach comparison

Approach Separate state Separate credentials Duplication Best for
Directory per environment ✓ ✓ Thin root modules repeat wiring The default for most teams
One root + -var-file + partial backend ✓ Possible None Small estates with a wrapper or CI-only applies
CLI workspaces ✓ (same backend) ✗ usually shared None Ephemeral copies of one environment
Terragrunt ✓ ✓ Minimal 20+ stacks, many environments × regions
Environments-as-data (YAML + one root) ✓ Possible None Many similar environments generated from data
HCP Terraform Stacks / workspaces ✓ ✓ Minimal Teams on HCP Terraform

Directory per environment

live/
├── modules/                       # or a separate, versioned modules repo
├── dev/
│   └── canadacentral/
│       └── network/
│           ├── main.tf            # module calls
│           ├── backend.tf         # literal backend for dev
│           ├── providers.tf       # dev subscription
│           ├── variables.tf
│           └── terraform.tfvars   # dev values
├── test/  (same shape)
└── prod/
    ├── canadacentral/network/
    └── canadaeast/network/        # DR region

Each leaf is a complete root module. cd live/prod/canadacentral/network && terraform plan can only ever touch prod's network state, using prod's backend.

Reducing the duplication: root modules should be thin, mostly module calls plus wiring. If dev/network/main.tf and prod/network/main.tf are 200 lines and nearly identical, move the shared part into a composition module so each root becomes:

module "network" {
  source  = "gitlab.example.com/acme/network-stack/azurerm"
  version = "~> 3.2"

  environment   = var.environment
  address_space = var.address_space
  subnets       = var.subnets
  tags          = local.tags
}

Now diff dev/.../terraform.tfvars prod/.../terraform.tfvars shows every environmental difference, and a module version bump is how a change moves from dev to prod.

One root module, per-environment var files and backends

network/
├── main.tf
├── variables.tf
├── backend.tf             # partial: backend "azurerm" { container_name = "tfstate" }
└── env/
    ├── dev.backend.hcl
    ├── dev.tfvars
    ├── prod.backend.hcl
    └── prod.tfvars
terraform init -reconfigure -backend-config=env/prod.backend.hcl
terraform plan -var-file=env/prod.tfvars -out=prod.tfplan

No duplication at all, but nothing stops -backend-config=env/prod.backend.hcl with -var-file=env/dev.tfvars. Make the pairing impossible to get wrong:

  • A wrapper script that takes the environment name once (example).
  • A guard inside the configuration:

```hcl data "azurerm_subscription" "current" {}

resource "terraform_data" "env_guard" { lifecycle { precondition { condition = data.azurerm_subscription.current.subscription_id == var.expected_subscription_id error_message = "Credentials point at ${data.azurerm_subscription.current.display_name}, but tfvars are for ${var.environment}." } } } ```

  • CI-only applies, so humans only ever plan locally.

Workspaces (for ephemeral copies only)

terraform workspace new mr-1234
terraform apply -var-file=env/dev.tfvars
terraform workspace select default && terraform workspace delete -force mr-1234

Fine for per-merge-request preview environments: same shape as dev, temporary, cheap. Not for dev/test/prod, because workspaces share the backend (and usually credentials) and the current workspace is invisible state on your machine. See state: workspaces.

Terragrunt

Terragrunt generates the backend and provider blocks from the folder path and lets each environment be a few lines of inputs per component. It also adds a cross-stack dependency graph (run --all). Worth it once you have many stacks × environments × regions. Full guide: Terragrunt.

Environments as data

Put each environment's description in a data file and have one root module read it:

# envs/prod.yaml
subscription_id: "00000000-0000-0000-0000-000000000000"
location: canadacentral
tier: large
network:
  address_space: ["10.30.0.0/16"]
  subnets:
    aks:  { address_prefix: "10.30.0.0/22" }
    data: { address_prefix: "10.30.4.0/24" }
features:
  private_endpoints: true
  zone_redundant: true
locals {
  env = yamldecode(file("${path.module}/envs/${var.environment}.yaml"))
}

module "network" {
  source        = "../modules/network"
  address_space = local.env.network.address_space
  subnets       = local.env.network.subnets
}

The YAML files can be validated with a JSON Schema in CI, generated by tooling, or read by other systems (your docs site, a CMDB). The variable that selects the file still has to be paired with the right backend, so combine this with directory-per-env or a wrapper.

Capabilities, not environment names

The most common design smell in multi-environment Terraform:

# ❌ inside a module
sku            = var.environment == "prod" ? "P2v3" : "B1"
zone_redundant = var.environment == "prod"

Every new environment ("perf", "uat", "prod-eu") means editing the module. Instead, the module exposes capabilities and the environment's inputs choose them:

# ✅ module
variable "sku" {
  type = string
}

variable "zone_redundant" {
  type    = bool
  default = false
}

# ✅ prod.tfvars
sku            = "P2v3"
zone_redundant = true

When many values move together, a tier map keeps tfvars short:

locals {
  tiers = {
    small  = { app_sku = "B1",   sql_sku = "GP_S_Gen5_2", min_replicas = 1, zone_redundant = false }
    medium = { app_sku = "P1v3", sql_sku = "GP_Gen5_4",   min_replicas = 2, zone_redundant = false }
    large  = { app_sku = "P2v3", sql_sku = "BC_Gen5_8",   min_replicas = 3, zone_redundant = true }
  }
  tier = local.tiers[var.tier]
}

Per-environment identity and isolation

  • One subscription (or AWS account, GCP project) per environment, not just one resource group. Subscriptions give hard RBAC, policy, quota and billing boundaries.
  • One pipeline identity per environment, federated to the CI environment (GitLab environment:, GitHub environments) so a dev job can't request a prod token. See security.
  • One state store per environment in that environment's subscription.
  • Don't hard-code subscription and tenant IDs in .tf files. Put them in tfvars or let the identity determine them (ARM_SUBSCRIPTION_ID), and add the guard above so a mismatch fails loudly.

Multiple regions

Treat region as another dimension of the directory tree or the data file:

prod/
├── canadacentral/{network,data,compute}
└── canadaeast/{network,data,compute}

Keep regions in separate states so a regional outage or a bad apply in one region can't block the other. For resources that span regions (global DNS, Front Door, geo-replication pairs), have a global/ stack or use multiple provider configurations.

Promotion

How a change moves from dev to prod:

Model How Notes
Module version bump per environment Release module v3.3 → bump dev → bump test → bump prod Clear, auditable; works with separate repos
Same commit, staged applies One MR; CI applies dev, then test, then prod with manual gates Simple; every env runs HEAD of the live repo
Branch per environment dev, test, prod branches merged forward Avoid. Merges get messy and environments drift

Whatever you choose, the plan that was reviewed should be the plan that gets applied: save it with -out and apply that file, or re-plan at apply time and fail if it differs. Details in CI/CD.

Keeping environments from drifting apart

  • A CI check that all environments are within N versions of each module.
  • A scheduled plan -detailed-exitcode per environment for drift.
  • terraform test runs against the dev tfvars to catch breakage before promotion.
  • Review tfvars diffs between environments periodically. Differences that nobody can explain are bugs waiting to happen.
in this section
* architecting terraform environments and modules