Skip to Content

Terraform Field Guide · Chapter 7 of 12

Many environments from one codebase

Dev, staging and production should be the same system at different sizes. Getting there takes two things at once: shared code so they cannot drift apart, and separate state and credentials so a mistake in one cannot reach the others. Compare the common layouts, then build the one this guide uses.

  • 45 min
  • Intermediate
  • Hands-on
  • Free

By , founding engineer running Terraform in production. Updated .

one repositorygitmodules/envs/devenvs/stagingenvs/proddev accountstate: dev/terraform.tfstatetf-dev rolestaging accountstate: staging/terraform.tfstatetf-staging roleprod accountstate: prod/terraform.tfstatetf-prod roleSeparate state, separate accessa mistake in dev cannot reach prod
The chapter in one pictureShared code for consistency, separate state and credentials for safety.

By the end you can

0 of 5

What should differ

An environment should differ from another by its inputs: sizes, counts, names, address ranges, which alarms page someone at night. It should not differ by its structure. If production has a resource that staging lacks, that should be a deliberate variable, not an accident.

Fine to differShould be the same
Instance sizes and countsWhich resources exist
Number of availability zonesNetwork layout and security group rules
Names, domains, CIDR rangesEncryption, logging and backups being on
Alarm thresholds and who gets pagedModule versions, once a change has been promoted

Three layouts

There are three common ways to lay out the code. Each looks fine on day one. Run each through a normal month:

Interactive · Laying out environments

Pick a layout, then see how it handles a normal month

    Folder per environment

    Each environment is a small root module that does three things: configures its backend, configures its provider, and calls the shared modules with its own inputs.

    envs/prod/main.tf
    terraform {
      backend "s3" {
        bucket       = "acme-terraform-state"
        key          = "prod/terraform.tfstate"
        region       = "eu-west-1"
        use_lockfile = true
      }
    }
    
    provider "aws" {
      region = "eu-west-1"
    
      assume_role {
        role_arn = "arn:aws:iam::111122223333:role/terraform-prod"
      }
    
      default_tags {
        tags = { environment = "prod", managed_by = "terraform" }
      }
    }
    
    module "network" {
      source   = "../../modules/network"
      name     = "prod"
      cidr     = var.cidr
      az_count = var.az_count
    }
    
    module "shop" {
      source        = "../../modules/service"
      name          = "shop-prod"
      desired_count = var.shop_count
      subnet_ids    = module.network.private_subnet_ids
    }
    Prod's own state file and its own lock. envs/dev uses dev/terraform.tfstate.
    Terraform runs as a prod-only role. The dev folder assumes a dev role, in the dev account.
    Every resource is tagged with its environment, which makes cost reports and clean-up easy.
    The shared code. Pin a version (chapter 6) when modules live in their own repository.
    The difference between environments is data, in a tfvars file.

    The differences live in one small file per environment. Comparing staging with prod is a diff of a few lines:

    envs/dev/terraform.tfvars
    cidr       = "10.10.0.0/16"
    az_count   = 1
    shop_count = 1
    envs/prod/terraform.tfvars
    cidr       = "10.30.0.0/16"
    az_count   = 3
    shop_count = 4

    Yes, every environment repeats the backend and provider blocks. That small repetition is deliberate: it is exactly the part that must differ. Tools such as Terragrunt can generate it if you end up with dozens of environments; with a handful, plain folders are easier to follow.

    State, accounts and roles

    Separate folders are the first wall. Make the others match:

    • Separate state. A different key per environment, so a broken apply in dev cannot corrupt prod's state, and locks do not block each other.
    • Separate accounts. Dev and prod in different AWS accounts, under one AWS Organization. It is the strongest boundary AWS offers, and it makes the bill per environment obvious.
    • Separate roles. Terraform for prod assumes a prod role that only the prod pipeline can use. A laptop with dev credentials cannot plan prod, let alone apply it.

    Promoting a change

    With this layout, a change moves through environments the same way an application release does:

    1. Merge the module change and tag it, for example v1.4.0.
    2. Bump envs/dev to v1.4.0. Read the plan, apply, check the service.
    3. Do the same for staging. This plan should look identical to dev's, apart from names and sizes. If it does not, find out why before going further.
    4. Bump prod. By now the plan holds no surprises; you have read it twice already.

    Chapter 10 automates exactly this: a plan on every pull request, and applies that run environment by environment.

    Hands-on: two environments, one module

    Build the folder layout locally. Each environment folder gets its own state automatically, because state lives with the folder you run in.

    Layout
    mkdir -p modules/app envs/dev envs/prod
    .
    ├── modules/app/main.tf
    └── envs/
        ├── dev/main.tf
        └── prod/main.tf
    modules/app/main.tf
    variable "env" {
      type = string
    }
    
    variable "replicas" {
      type = number
    }
    
    resource "local_file" "config" {
      filename = "${path.root}/out/app.json"
      content  = "${jsonencode({ env = var.env, replicas = var.replicas })}\n"
    }
    The folder you run Terraform in, so each environment writes into its own out/ folder.
    envs/dev/main.tf
    terraform {
      required_providers {
        local = { source = "hashicorp/local", version = "~> 2.5" }
      }
    }
    
    module "app" {
      source   = "../../modules/app"
      env      = "dev"
      replicas = 1
    }
    Two levels up, then into modules. Every environment points at the same code.

    Copy envs/dev/main.tf to envs/prod/main.tf and change it to env = "prod" and replicas = 3. Then apply each one:

    Apply both
    cd envs/dev && terraform init && terraform apply -auto-approve && cd ../..
    cd envs/prod && terraform init && terraform apply -auto-approve && cd ../..
    cat envs/dev/out/app.json envs/prod/out/app.json
    ls envs/*/terraform.tfstate
    {"env":"dev","replicas":1}
    {"env":"prod","replicas":3}
    envs/dev/terraform.tfstate
    envs/prod/terraform.tfstate
    two state files
    Compare with chapter 4, where planning prod wanted to destroy dev. Each environment now has its own state, so neither can touch the other.

    Mini mission

    Add staging, and change only prod

    Add a staging environment with 2 replicas. Then change prod to 4 replicas. Run plan in all three folders: which ones show changes?

    Reveal one safe solution
    Terminal
    mkdir -p envs/staging
    sed 's/"dev"/"staging"/; s/replicas = 1/replicas = 2/' envs/dev/main.tf > envs/staging/main.tf
    cd envs/staging && terraform init && terraform apply -auto-approve && cd ../..
    

    After changing prod to 4, only envs/prod shows a plan (the file is replaced with the new content). Dev and staging say No changes: separate roots, separate state, and the module itself did not change. If you had changed the module instead, all three would show a plan, which is why module changes are promoted one environment at a time.

    Check yourself

    Quiz

    0 of 5 answered

    1. 1. Which difference between staging and prod is a smell?
    2. 2. Why are CLI workspaces a poor fit for dev and prod?
    3. 3. What is the main reason to put prod in a separate AWS account?
    4. 4. A module change is merged. What is the safe order?
    5. 5. In a folder-per-environment layout, what makes each environment's state separate?

    Further reading