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 Joshua Sequeira, founding engineer running Terraform in production. Updated .
By the end you can
0 of 5
Live lab in this chapter
A real-feeling terminal and a live cluster map, right in your browser. Every command block below has a ▶ Run in lab button.
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 differ | Should be the same |
|---|---|
| Instance sizes and counts | Which resources exist |
| Number of availability zones | Network layout and security group rules |
| Names, domains, CIDR ranges | Encryption, logging and backups being on |
| Alarm thresholds and who gets paged | Module 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.
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:
cidr = "10.10.0.0/16"
az_count = 1
shop_count = 1cidr = "10.30.0.0/16"
az_count = 3
shop_count = 4Yes, 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:
- Merge the module change and tag it, for example
v1.4.0. - Bump
envs/devtov1.4.0. Read the plan, apply, check the service. - 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.
- 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.
mkdir -p modules/app envs/dev envs/prod
.
├── modules/app/main.tf
└── envs/
├── dev/main.tf
└── prod/main.tfvariable "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.
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:
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.tfstatetwo 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
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