AWS Builder Center

Managing Dev, Staging and Prod with Terraform: Modules and Environment Folders

How to organize Terraform for multiple environments using shared modules and one folder per environment

Managing Dev, Staging and Prod with Terraform: Modules and Environment Folders

This post shows how to organize Terraform for multiple environments using shared modules and one folder per environment. The modules define the infrastructure once, and each environment folder (dev, staging and prod) calls those modules with its own sizes, settings and AWS account. Every environment then runs the same tested code, and the only differences are the values each one sets.
The example is a three-tier web app:
  • Web tier: an Application Load Balancer in public subnets
  • App tier: Amazon EC2 instances in an Auto Scaling group in private subnets
  • Data tier: an Amazon RDS for PostgreSQL database in isolated subnets

Prerequisites

  • Basic familiarity with Terraform ( terraform init ,  plan ,  apply )
  • One AWS account per environment is recommended, for example dev, staging and prod accounts in AWS Organizations
  • Bootstrapped per account (not covered here): an S3 bucket for Terraform state, an AWS CLI profile for local use, and an IAM OIDC identity provider with plan and apply roles for GitLab CI/CD

Step 1: Understand the two building blocks

The setup has two kinds of folders.
  1. Modules ( modules/ ): A module is a reusable set of Terraform files that describes one part of the infrastructure. This post has one module per tier: network (VPC and subnets), app (load balancer and Auto Scaling group) and database (RDS for PostgreSQL). A module doesn't know which environment it's deployed to. Anything that can differ between environments, such as instance size or the number of Availability Zones, is an input variable.
  1. Environment folders ( envs/dev ,  envs/staging ,  envs/prod ): Each folder calls the same three modules and sets the values for that environment in its terraform.tfvars, such as small instances for dev and larger ones for prod. Each folder also has its own backend.tf, so every environment keeps its own state file in its own AWS account.
Think of a module as a blueprint and an environment folder as a building made from it. You fix the blueprint once, and every building gets the fix.
Benefits of this structure:
  • Write once, reuse everywhere: The infrastructure code lives in one place, so dev, staging and prod can't drift apart through copy and paste.
  • Differences are easy to see: What makes prod different from dev is visible from terraform.tfvars
  • Smaller blast radius: Separate state files and AWS accounts isolates the blast radius between dev, staging, prod
  • Safe promotion: A module change is tested in dev and staging before it reaches prod, through the same pipeline.
  • One branch to follow: Every environment lives on main, so the repo always shows what's deployed everywhere.

Step 2: Lay out the repository

infra/
├── modules/
│ ├── network/ # VPC and subnets for all three tiers
│ │ ├── main.tf
│ │ ├── variables.tf
│ │ ├── outputs.tf
│ │ └── versions.tf
│ ├── app/ # load balancer + EC2 Auto Scaling group
│ │ ├── main.tf
│ │ ├── variables.tf
│ │ ├── outputs.tf
│ │ └── versions.tf
│ └── database/ # RDS for PostgreSQL
│ ├── main.tf
│ ├── variables.tf
│ ├── outputs.tf
│ └── versions.tf
└── envs/
├── dev/
│ ├── backend.tf # dev state file location
│ ├── main.tf # calls the three modules
│ ├── outputs.tf
│ ├── providers.tf
│ ├── terraform.tfvars # dev sizes
│ ├── variables.tf
│ └── versions.tf
├── staging/
│ ├── backend.tf # staging state file location
│ ├── main.tf
│ ├── outputs.tf
│ ├── providers.tf
│ ├── terraform.tfvars # staging sizes
│ ├── variables.tf
│ └── versions.tf
└── prod/
├── backend.tf # prod state file location
├── main.tf
├── outputs.tf
├── providers.tf
├── terraform.tfvars # prod sizes
├── variables.tf
└── versions.tf
In the  envs  folder, the terraform files:
  • main.tf: Calls the network, app and database modules and connects them to each other.
  • terraform.tfvars: Define different values for different environments, such as instance sizes, the number of Availability Zones and deletion protection.
  • backend.tf: Tells Terraform where to store prod's state file, the S3 bucket in the prod account.
  • outputs.tf: Shows the terraform outputs generated after terraform apply eg. load balancer DNS name
  • providers.tf: Configures the AWS provider with the Region and the default tags for every resource.
  • variables.tf: declares the inputs prod accepts, which terraform.tfvars fills in.
  • versions.tf: pins the Terraform and AWS provider versions so every run behaves the same.

Step 3: Write the modules

Database module

 modules/database/main.tf  creates the database and only lets the app tier connect to it:
resource "aws_db_subnet_group" "this" {
name = var.name
subnet_ids = var.db_subnet_ids
}

resource "aws_db_instance" "this" {
identifier = var.name
engine = "postgres"
engine_version = var.engine_version
allow_major_version_upgrade = true # allows upgrades such as 17 -> 18
apply_immediately = true # apply changes on terraform apply, not in the next maintenance window
instance_class = var.instance_class
allocated_storage = var.allocated_storage_gib
db_name = "app"
username = "app_admin"
manage_master_user_password = true # password stored in AWS Secrets Manager
db_subnet_group_name = aws_db_subnet_group.this.name
vpc_security_group_ids = [aws_security_group.db.id]
multi_az = var.multi_az
storage_encrypted = true
deletion_protection = var.deletion_protection
skip_final_snapshot = !var.deletion_protection
}

resource "aws_security_group" "db" {
name = "${var.name}-db"
vpc_id = var.vpc_id
}

# Only the app servers can reach the database
resource "aws_vpc_security_group_ingress_rule" "from_app" {
security_group_id = aws_security_group.db.id
referenced_security_group_id = var.app_security_group_id
ip_protocol = "tcp"
from_port = 5432
to_port = 5432
}
 modules/database/variables.tf : Lists the inputs the database module accepts.
variable "name" {
type = string
description = "Name prefix for all resources."
}

variable "vpc_id" {
type = string
description = "VPC to deploy into."
}

variable "db_subnet_ids" {
type = list(string)
description = "Subnets for the database."
}

variable "app_security_group_id" {
type = string
description = "Security group allowed to connect to the database."
}

variable "engine_version" {
type = string
description = "PostgreSQL engine version, for example 17 or 18.2."
}

variable "instance_class" {
type = string
description = "RDS instance class."
}

variable "allocated_storage_gib" {
type = number
description = "Storage size in GiB."
}

variable "multi_az" {
type = bool
description = "Keep a standby copy of the database in a second Availability Zone."
}

variable "deletion_protection" {
type = bool
description = "Block deletion of the database."
}
 modules/database/outputs.tf : Lists the values the database module returns, such as the database endpoint, so other modules can use them
output "db_endpoint" {
description = "Connection endpoint of the database."
value = aws_db_instance.this.endpoint
}
The  network  and  app  modules follow the same pattern as the database module above:
  •  network : creates the VPC, with public, app and database subnets in each Availability Zone, plus the internet gateway, NAT gateways and route tables.
  •  app : creates the Application Load Balancer in the public subnets and an EC2 Auto Scaling group in the app subnets.

Step 4: Use the modules in each environment

 main.tf 

 envs/<env>/main.tf  connects the three tiers. The network outputs feed the app and database modules, and the app's security group feeds the database:
module "network" {
source = "../../modules/network"

name = "webapp-${var.environment}"
cidr_block = var.vpc_cidr
az_count = var.az_count
single_nat_gateway = var.single_nat_gateway
}

module "app" {
source = "../../modules/app"

name = "webapp-${var.environment}"
vpc_id = module.network.vpc_id
public_subnet_ids = module.network.public_subnet_ids
app_subnet_ids = module.network.app_subnet_ids
instance_type = var.app_instance_type
min_size = var.app_min_size
max_size = var.app_max_size
}

module "database" {
source = "../../modules/database"

name = "webapp-${var.environment}"
vpc_id = module.network.vpc_id
db_subnet_ids = module.network.db_subnet_ids
app_security_group_id = module.app.app_security_group_id
engine_version = var.db_engine_version
instance_class = var.db_instance_class
allocated_storage_gib = var.db_storage_gib
multi_az = var.db_multi_az
deletion_protection = var.db_deletion_protection
}

 variables.tf 

 envs/<env>/variables.tf  declares the inputs used in  envs/<env>/main.tf 
variable "environment" {
type = string
description = "Environment name, used in resource names and tags."
}

variable "account_id" {
type = string
description = "AWS account ID this environment must deploy to."
}

... # Truncated

variable "db_deletion_protection" {
type = bool
description = "Block deletion of the database."
}

 backend.tf 

 envs/<env>/backend.tf  points each environment at an Amazon S3 state bucket in its own account, so running  terraform apply  in dev won't affect prod resources as they are in separate AWS accounts. These S3 buckets are created as part of the pre-requisite.
 envs/dev/backend.tf :
terraform {
backend "s3" {
bucket = "tfstate-111111111111-us-east-1" # bucket in the dev account
key = "webapp/terraform.tfstate"
region = "us-east-1"
encrypt = true
use_lockfile = true # S3 native state locking (Terraform 1.10+)
}
}
 envs/prod/backend.tf :
terraform {
backend "s3" {
bucket = "tfstate-333333333333-us-east-1" # bucket in the prod account
key = "webapp/terraform.tfstate"
region = "us-east-1"
encrypt = true
use_lockfile = true
}
}
Other files to be defined:  envs/<env>/outputs.tf ,  envs/<env>/providers.tf ,  envs/<env>/versions.tf .

 terraform.tfvars : Define Differently for each Environment

 main.tf  and  variables.tf  describe what each environment builds, and they're identical everywhere.  terraform.tfvars  supplies the values: how big, how many and which version. Terraform loads  terraform.tfvars  automatically from the folder you run it in, so  terraform plan  in  envs/dev  uses dev's values and  terraform plan  in  envs/prod  uses prod's.
Why this split works well with modules:
  • Write the code once. The network, app and database code exists only in  modules/ . No environment rewrites or copies a resource. Each one only states its own numbers.
  • Change one environment at a time. Upgrading dev's database or adding app servers to prod is a quick edit in that environment's  terraform.tfvars . The other environments don't change.
  • Easy reviews. Comparing  envs/staging/terraform.tfvars  with  envs/prod/terraform.tfvars  shows every difference between the two environments in one view.
  • No forgotten values. Environment-specific variables have no default, so Terraform stops with an error if a  terraform.tfvars  file leaves one out.
  • Easy new environments. To add an environment, such as  envs/qa , copy a folder, then change its  terraform.tfvars  and  backend.tf .
 envs/dev/terraform.tfvars :
environment = "dev"
account_id = "111111111111"
vpc_cidr = "10.10.0.0/16"
az_count = 2
single_nat_gateway = true
app_instance_type = "t3.small"
app_min_size = 1
app_max_size = 2
db_engine_version = "17"
db_instance_class = "db.t4g.micro"
db_storage_gib = 20
db_multi_az = false
db_deletion_protection = false
 envs/staging/terraform.tfvars : Staging env will mimick prod's environment as closely as possible
environment = "staging"
account_id = "222222222222"
vpc_cidr = "10.20.0.0/16"
az_count = 2
single_nat_gateway = true
app_instance_type = "m7i.large"
app_min_size = 2
app_max_size = 4
db_engine_version = "17"
db_instance_class = "db.r7g.large"
db_storage_gib = 100
db_multi_az = true
db_deletion_protection = false
 envs/prod/terraform.tfvars :
environment = "prod"
account_id = "333333333333"
vpc_cidr = "10.30.0.0/16"
az_count = 3
single_nat_gateway = false
app_instance_type = "m7i.large"
app_min_size = 3
app_max_size = 9
db_engine_version = "17"
db_instance_class = "db.r7g.large"
db_storage_gib = 200
db_multi_az = true
db_deletion_protection = true
The full comparison:
Setting
dev
staging
prod
AWS account and state file
dev account
staging account
prod account
Availability Zones
2
2
3
NAT gateways
1 shared
1 shared
1 per AZ
App servers
1–2 ×  t3.small 
2–4 ×  m7i.large 
3–9 ×  m7i.large 
Database
 db.t4g.micro , single-AZ
 db.r7g.large , Multi-AZ
 db.r7g.large , Multi-AZ, deletion protection
Who applies changes
pipeline
pipeline
pipeline, after approval
If prod needs something the other environments don't, such as an AWS WAF web ACL in front of the load balancer, you can add it only in  envs/prod/main.tf .

Step 5: Setting up the CI/CD for Dev, Staging and Prod

In this blog, we are using Gitlab for CI/CD. All three environments are deployed by GitLab-hosted runners.

Set up GitLab

  1. Protect  main : in Settings > Repository > Protected branches, allow merges from maintainers only, and allow no direct pushes. Changes then reach  main  only through merge requests.
  1. Add the prod approval: in Settings > CI/CD > Protected environments, protect  production , choose the Approvers, and set Required approvals to  1 .
  1. Add  .gitlab-ci.yml  at the root of the repository. This is the configuration file that defines your Gitlab CI/CD pipeline. GitLab reads this file and runs its jobs on GitLab-hosted runners.

Add  .gitlab-ci.yml 

workflow:
rules: # run for merge requests and for main only
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH

stages: [plan, apply]

... # Truncated. Out of scope for this blog.

Example: Resize the database in staging, then prod

A simple example where Prod needs a larger database, so its instance class changes from  db.r7g.large  to  db.r7g.xlarge . Staging runs the same size as prod, so it gets the change first, and prod follows once staging looks healthy. Dev stays on  db.t4g.micro .
Merge request 1: staging
  1. Create a branch, and change one line in  envs/staging/terraform.tfvars :
db_instance_class = "db.r7g.xlarge" # was "db.r7g.large"
  1. Push the branch and open a merge request. The pipeline plans all three environments:
  •  plan:dev  and  plan:prod : no changes
  •  plan:staging :  1 to change, 0 to destroy , with  instance_class  changing on  module.database.aws_db_instance.this 
  1. A reviewer approves the merge request, and you merge it.
  1. The  main  pipeline runs  apply:dev  (no changes), then  apply:staging , which resizes the staging database.  apply:prod  has nothing to change.
  1. Check staging:
  • Confirm the new size:
aws rds describe-db-instances \
--db-instance-identifier webapp-staging \
--query "DBInstances[].[DBInstanceClass,DBInstanceStatus]" \
--profile infra-staging-readonly
  • Expect  db.r7g.xlarge  with status  available .
  • Run the app's tests against staging, and check the database's CloudWatch metrics, such as  CPUUtilization  and  DatabaseConnections .
If anything fails, fix or revert it in staging. Prod hasn't changed.
Merge request 2: prod
  1. Once staging is healthy, start a new branch from the updated  main , and make the same change in  envs/prod/terraform.tfvars :
db_instance_class = "db.r7g.xlarge" # was "db.r7g.large"
  1. Push the branch and open a merge request. Now only  plan:prod  shows  1 to change, 0 to destroy .
  1. A reviewer approves the merge request, and you merge it.
  1. The  main  pipeline runs  apply:dev  and  apply:staging  (no changes), then pauses at  apply:prod .
  1. An approver opens the pipeline, reviews the  plan:prod  output, and selects Approve. Because of the brief failover, approve during a low-traffic period. Then someone allowed to deploy starts  apply:prod .
  1. Confirm the new size with the same  describe-db-instances  command, using  webapp-prod  and the prod profile.

Summary

Shared Terraform modules keep dev, staging and prod on the same Terraform code, and each environment's  terraform.tfvars  shows exactly how it differs. Separate state files and AWS accounts helps to isolate each environment, and every infrastructure change goes through dev and staging CI/CD pipeline before it reaches prod. This post covers one approach: a separate folder for each environment. Other options, such as a Git branch per environment or Terraform workspaces, are not discussed in this blog.
Things to watch out for:
  • A module change reaches every environment. The pipeline order (dev, then staging, then prod) is your safety net. For stricter control, version your modules and let each environment choose when to upgrade.
  • Environment folders can drift. Keep them thin, and compare them during reviews.
  • Copying a folder copies its backend. When you create a new environment from an existing one, update the state file location.
  • Plans and state can contain secrets. Limit who can read them.

References

Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article