Terraform Modules, Remote State and Environments: One Codebase for Staging and Production
Three modules, two environments, one main.tf. Staging plans 3 resources and production 5, because only the tfvars differ. Each keeps its state in its own bucket, and while staging's apply waits at the prompt, a second plan is refused with a 412 and the lock's details. Afterwards the plan says No changes.
What you will learn
- Split infrastructure into network, database and service modules
- Run staging and production from the same main.tf with their own tfvars and backend
- Keep each environment's state in its own S3 bucket with a lock file, and see a second run refused
- Pin module versions and run terraform plan on every pull request
Before you start
- Terraform for a Help Desk: One Module, Two Provider Blocks (AWS and LocalStack), Checked in Python Before Plan
- Docker Compose basics
The previous Terraform lecture described an app once and handed it to two providers. That works for one person on one laptop. A team needs three more things: pieces that can be reused, separate environments that can't step on each other, and state that lives somewhere shared and safe. This article adds all three to Relay's infrastructure.
The runs used Terraform 1.13.5 with the Docker provider standing in for AWS (a network for the VPC, containers for the database and the service), and MinIO standing in for S3 as the state store.
Three modules, two folders
modules/
network/main.tf
database/main.tf
service/main.tf
envs/
staging/ main.tf terraform.tfvars backend.tf
production/ main.tf terraform.tfvars backend.tf
Each module is a function: variables in, resources inside, outputs back. network makes the network, database the database, and service the API, with a replicas count. The main.tf in both environment folders is the same file:
module "network" {
source = "../../modules/network"
name = "relay-${var.environment}"
}
module "database" {
source = "../../modules/database"
name = "relay-${var.environment}"
network = module.network.name
password = var.db_password
}
module "service" {
source = "../../modules/service"
name = "relay-${var.environment}"
image = var.image
network = module.network.name
replicas = var.replicas
log_level = var.log_level
db_host = module.database.host
db_password = var.db_password
}
Modules connect through outputs: the service gets the network's name and the database's host. db_password is a variable marked sensitive = true, so Terraform hides it in plans and logs, and its value comes from the environment (TF_VAR_db_password), never from a file in the repo.
What differs: two small files
# envs/staging/terraform.tfvars
environment = "staging"
replicas = 1
log_level = "DEBUG"
image = "relay-api:latest" # on AWS: the ECR image
# envs/production/terraform.tfvars
environment = "production"
replicas = 3
log_level = "INFO"
image = "relay-api:latest" # on AWS: the ECR image
# envs/staging/backend.tf (production uses relay-tfstate-production)
terraform {
backend "s3" {
bucket = "relay-tfstate-staging"
key = "relay/terraform.tfstate"
region = "eu-west-2"
encrypt = true
use_lockfile = true # a lock object next to the state
}
}
Values in terraform.tfvars, state location in backend.tf. Everything else is shared. A separate bucket per environment means a mistake in staging can't even read production's state. (For MinIO, a small local.s3.tfbackend file adds the local endpoint and sets encrypt = false, because this MinIO has no KMS. On AWS that file isn't used.)
Init, validate, plan
terraform -chdir=envs/staging init -backend-config=../../local.s3.tfbackend said Successfully configured the backend "s3"! and created .terraform.lock.hcl, which pins the provider versions. Production the same. validate answered Success! The configuration is valid. Then the two plans:
| Staging | Production | |
|---|---|---|
| Network | relay-staging-net | relay-production-net |
| Database | relay-staging-db | relay-production-db |
| API containers | relay-staging-api-1 | relay-production-api-1 to -3 |
| Plan | Plan: 3 to add, 0 to change, 0 to destroy. | 5 to add |
Same code, different counts, because replicas is 1 or 3.
State and the lock
Before any apply, the buckets were empty. Staging's apply was started and left waiting at its "yes" prompt. The staging bucket now held relay/terraform.tfstate.tflock: use_lockfile = true writes that object when a run starts and deletes it when it ends. A second plan on staging, in another terminal:
Error: Error acquiring the state lock
Error message: operation error S3: PutObject, https response error
StatusCode: 412, ...
Lock Info:
ID: 350835f2-e1c2-2fc6-c9a8-cf3a7099c921
Path: relay-tfstate-staging/relay/terraform.tfstate
Operation: OperationTypeApply
Who: root@5a30e7ae4d3b
412 is "precondition failed": Terraform tried to create the lock object only if it didn't exist, and it did. The message says who holds the lock and what they're doing. Without the lock, two applies could each write their own version of the state, and one would be lost.
After the apply, the bucket held only terraform.tfstate, the lock gone. Production applied too, and docker ps showed relay-production-api-1 to -3, relay-production-db, relay-staging-api-1 and relay-staging-db. state list for staging had three entries, one per resource, and a fresh plan said No changes. Your infrastructure matches the configuration. Then both were destroyed.
Pin the version, plan on every pull request
While modules live in the same repo, source = "../../modules/service" is fine. Once they move to their own repository, pin a tag, so a change to the module doesn't reach production by surprise:
source = "git::https://github.com/<your-org>/relay-modules.git//service?ref=v1.2.0"
And the project's terraform-plan.yml runs on pull requests that touch modules/** or envs/**: fmt -check, init, validate, then plan -lock-timeout=120s, and posts the plan as a comment on the pull request. It gets AWS access by assuming a role through GitHub's OIDC login, so no AWS keys are stored in GitHub. That workflow wasn't run here; it's shown as a file.
Common mistakes
- One state for every environment. A bad apply in staging can then change production. Separate states, separate buckets.
- State on a laptop. Nobody else can plan, and the file is one disk failure from gone.
-lock=falseto "get past" a lock. Find out who holds it first. It's usually a run that's still going.- Secrets in
terraform.tfvars. They end up in git. Pass them asTF_VAR_environment variables and mark them sensitive. (They are still stored in the state, which is one more reason to keep the state bucket private and encrypted.) - Copying
main.tfper environment and editing it. The copies drift. Keep one file and change only the values.
Try it yourself
Change production's replicas to 2 and run plan for both environments. What does each one want to do, and why does staging say nothing at all?
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Python Virtual Environments: One Project, One Toolbox
Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.
Git and GitHub Fundamentals: Commits, Branches, Push and Pull
The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.
Testing a FastAPI App with pytest: Three Small Tests
A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.
Config and Logging Instead of Hard-Coded Values in ML Training
Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.
