Terraform becomes difficult to manage when every environment is a copy of the last one. A change to a VPC is repeated in several folders, an application stack owns networking it should only consume, and a production plan becomes too large to review with confidence. Modularity solves those problems only when the boundaries are deliberate.
This walkthrough designs an AWS Terraform architecture that separates reusable building blocks from environment-specific composition. The result lets a platform team evolve common infrastructure without turning Terraform into a maze of nested modules or a collection of tightly coupled state files.
What you will build
We will model a typical AWS application platform made of:
- A VPC spanning multiple Availability Zones
- Public and private subnets, routing, and NAT gateways
- Security groups that express ingress and egress intent
- An Application Load Balancer (ALB)
- An ECS service that receives traffic only through the ALB
- Environment roots for development and production
- A remote state backend with state locking
The implementation examples use ECS, but the architectural approach also works for EC2, EKS, Lambda, RDS, and other AWS services.
Learning objectives
By the end, you should be able to:
- Choose useful Terraform module boundaries.
- Organize modules and environment roots in a predictable repository layout.
- Pass dependencies through module inputs and outputs instead of hiding them in nested modules.
- Isolate state so a change has an understandable blast radius.
- Apply conventions for versioning, validation, security, and promotion.
Prerequisites
You will need an AWS account, Terraform, AWS credentials with appropriately scoped permissions, and an S3 bucket for Terraform state. Run Terraform with a role or federated identity where possible; do not put long-lived AWS access keys in .tfvars files or source control.
The examples assume Terraform 1.10 or later so the S3 backend can use native S3 lockfiles. If your organization still uses DynamoDB locking, plan a migration: HashiCorp has deprecated DynamoDB-based locking for the S3 backend in favor of use_lockfile = true.
1. Start with architecture, not folders
A module is a collection of Terraform resources managed together. That does not mean every AWS resource deserves its own module. A helpful rule is:
Create a module for a cohesive capability with a stable interface that will be used in more than one place.
For example, a VPC, its subnets, route tables, and Internet/NAT connectivity form a cohesive networking capability. Putting each of those in a separate module makes simple changes hard to follow. On the other hand, embedding the VPC inside every application module makes the application impossible to place in an existing network.
Good boundaries usually align with an ownership boundary, a lifecycle boundary, or both:
| Capability | Typical owner | Why it is a module |
|---|---|---|
| Network | Platform team | VPC topology is shared and changes cautiously. |
| Security groups | Platform/security team | Rules are a reusable policy boundary. |
| ALB | Platform or application team | It has a focused interface: subnets, listener configuration, and target attachment. |
| ECS service | Application team | It packages an independently deployed workload. |
| Environment root | Platform team | It composes approved modules and contains environment-specific decisions. |
Avoid modules that merely wrap one resource without providing a policy, abstraction, or reuse benefit. They add an interface to learn but do not reduce complexity.
Keep composition shallow
Prefer a root module that places peer modules side by side and connects them through explicit inputs and outputs:
environment root
├── network
├── security
├── alb ← receives network outputs
└── ecs_service ← receives network, security, and ALB outputs
Do not make the ECS module create its own VPC, then make an ALB module create another security group inside it, then make a parent module discover those resources by name. A shallow module tree makes dependencies visible in the root configuration, lets modules be reused in new combinations, and avoids surprising ownership. HashiCorp similarly recommends a relatively flat module tree and composition at the calling layer.
2. Use a repository layout that distinguishes reuse from deployment
The following layout works well for a small-to-medium platform. It can later evolve into separate repositories for shared modules and live environments.
terraform-aws-platform/
├── bootstrap/
│ └── state-backend/
│ ├── main.tf
│ ├── outputs.tf
│ └── variables.tf
├── modules/
│ ├── network/
│ │ ├── main.tf
│ │ ├── variables.tf
│ │ ├── outputs.tf
│ │ └── README.md
│ ├── security-group/
│ ├── alb/
│ └── ecs-service/
├── environments/
│ ├── dev/
│ │ ├── backend.tf
│ │ ├── main.tf
│ │ ├── providers.tf
│ │ ├── variables.tf
│ │ ├── terraform.tfvars.example
│ │ └── versions.tf
│ └── prod/
│ └── ...
├── .gitignore
└── README.md
modules/ contains reusable building blocks. environments/ contains root modules: the directories from which an operator runs terraform plan and terraform apply. bootstrap/ is intentionally separate because a state backend must exist before other configurations can use it.
Within every reusable module, keep the basic shape consistent:
main.tfcontains resources and child-module calls.variables.tfdescribes the public input contract.outputs.tfexposes values callers legitimately need.README.mddescribes intended use, assumptions, inputs, outputs, and examples.
Terraform treats all .tf files in one directory as a single module; these filenames are for readers. The convention is still valuable because it makes every module navigable. It also follows HashiCorp’s recommended standard module structure.
3. Bootstrap remote state once
Terraform state maps configuration to real AWS objects. It is sensitive operational data and must not live on an engineer’s laptop or in Git. Use a dedicated S3 bucket, protect it with encryption and public-access blocking, and enable versioning so an accidental state overwrite can be recovered.
The bootstrap configuration is applied once using local state. Record the resulting bucket name and AWS Region in secure team documentation or your CI configuration.
# bootstrap/state-backend/main.tf
resource "aws_s3_bucket" "terraform_state" {
bucket = var.bucket_name
tags = {
ManagedBy = "Terraform"
Purpose = "terraform-state"
}
}
resource "aws_s3_bucket_versioning" "terraform_state" {
bucket = aws_s3_bucket.terraform_state.id
versioning_configuration {
status = "Enabled"
}
}
resource "aws_s3_bucket_server_side_encryption_configuration" "terraform_state" {
bucket = aws_s3_bucket.terraform_state.id
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "AES256"
}
}
}
resource "aws_s3_bucket_public_access_block" "terraform_state" {
bucket = aws_s3_bucket.terraform_state.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
Each environment root points to its own key in that shared bucket:
# environments/prod/backend.tf
terraform {
backend "s3" {
bucket = "acme-terraform-state-123456789012"
key = "platform/prod/terraform.tfstate"
region = "eu-west-1"
use_lockfile = true
encrypt = true
}
}
Use a unique key for every independently applied root module. Locking prevents concurrent writes, but it does not make an overly broad state file safer. Keep the credentials outside backend configuration; backend values can be recorded in Terraform’s working directory and saved plan files.
For larger organizations, place state in a dedicated AWS account and grant each deployment role only access to its allowed state prefix. A production role should not be able to read or write development state merely because both live in one bucket.
4. Define provider and naming conventions at the root
The root module should declare the Terraform and provider versions it supports. Commit .terraform.lock.hcl so CI and developer machines resolve the same provider builds.
# environments/prod/versions.tf
terraform {
required_version = ">= 1.10.0, < 2.0.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
Apply shared tags in the provider so resource modules cannot accidentally omit cost, ownership, or environment metadata:
# environments/prod/providers.tf
provider "aws" {
region = var.aws_region
default_tags {
tags = {
Application = var.application_name
Environment = var.environment
ManagedBy = "Terraform"
Owner = var.owner
}
}
}
Pass a small tags map to modules only when a caller needs to add module- or resource-specific tags. Do not repeat the global tags in every resource block.
5. Build the network module around intent
The networking module should accept the information needed to describe a network, not an entire application configuration. Its outputs should identify the resources downstream modules need to join.
# modules/network/variables.tf
variable "name" {
description = "Name prefix for networking resources."
type = string
}
variable "vpc_cidr" {
description = "IPv4 CIDR block for the VPC."
type = string
}
variable "availability_zones" {
description = "Availability Zones used for public and private subnets."
type = list(string)
validation {
condition = length(var.availability_zones) >= 2
error_message = "Provide at least two Availability Zones for a resilient deployment."
}
}
variable "public_subnet_cidrs" {
description = "One public subnet CIDR per Availability Zone."
type = list(string)
}
variable "private_subnet_cidrs" {
description = "One private subnet CIDR per Availability Zone."
type = list(string)
}
Use for_each or a keyed map when resource identity matters. It is safer than count for subnets because a new availability zone does not renumber existing addresses in state.
# modules/network/main.tf (excerpt)
locals {
azs = {
for index, az in var.availability_zones : az => {
public_cidr = var.public_subnet_cidrs[index]
private_cidr = var.private_subnet_cidrs[index]
}
}
}
resource "aws_vpc" "this" {
cidr_block = var.vpc_cidr
enable_dns_hostnames = true
enable_dns_support = true
tags = { Name = "${var.name}-vpc" }
}
resource "aws_subnet" "private" {
for_each = local.azs
vpc_id = aws_vpc.this.id
availability_zone = each.key
cidr_block = each.value.private_cidr
tags = { Name = "${var.name}-private-${each.key}" }
}
# modules/network/outputs.tf (excerpt)
output "vpc_id" {
description = "ID of the VPC created by this module."
value = aws_vpc.this.id
}
output "private_subnet_ids" {
description = "IDs of private subnets, suitable for internal workloads."
value = [for subnet in aws_subnet.private : subnet.id]
}
The full module would also create public subnets, an Internet gateway, NAT gateways, route tables, and associations. Those belong here because they implement one network topology. An ECS task definition, database password, or ALB listener rule does not.
6. Make dependencies explicit with inputs and outputs
An environment root should read like an architecture diagram. The following example creates a VPC, gives an ALB public subnets, then gives an ECS service private subnets and the security group it needs:
# environments/prod/main.tf
module "network" {
source = "../../modules/network"
name = "${var.application_name}-${var.environment}"
vpc_cidr = "10.40.0.0/16"
availability_zones = ["eu-west-1a", "eu-west-1b"]
public_subnet_cidrs = ["10.40.0.0/24", "10.40.1.0/24"]
private_subnet_cidrs = ["10.40.10.0/24", "10.40.11.0/24"]
}
module "alb_security_group" {
source = "../../modules/security-group"
name = "${var.application_name}-${var.environment}-alb"
vpc_id = module.network.vpc_id
ingress_rules = [{
description = "HTTPS from the internet"
from_port = 443
to_port = 443
protocol = "tcp"
cidr_ipv4 = "0.0.0.0/0"
}]
}
module "app_security_group" {
source = "../../modules/security-group"
name = "${var.application_name}-${var.environment}-app"
vpc_id = module.network.vpc_id
ingress_rules = [{
description = "Application traffic from the ALB"
from_port = var.container_port
to_port = var.container_port
protocol = "tcp"
referenced_security_group_id = module.alb_security_group.id
}]
}
module "alb" {
source = "../../modules/alb"
name = "${var.application_name}-${var.environment}"
subnet_ids = module.network.public_subnet_ids
security_group_ids = [module.alb_security_group.id]
target_port = var.container_port
}
module "ecs_service" {
source = "../../modules/ecs-service"
name = "${var.application_name}-${var.environment}"
subnet_ids = module.network.private_subnet_ids
security_group_ids = [module.app_security_group.id]
target_group_arn = module.alb.target_group_arn
container_image = var.container_image
container_port = var.container_port
}
The ordering is inferred from real references: the ALB module cannot be planned without subnets, and the ECS service cannot be created without its target group. Avoid depends_on between modules unless there is a real ordering relationship Terraform cannot infer from values. Explicit data flow produces a more precise graph than an artificial dependency.
7. Design module interfaces as contracts
A reusable module is an internal product. Its variables and outputs are its API.
Inputs: minimal, typed, and validated
- Require values that must differ by use, such as
vpc_idorsubnet_ids. - Provide defaults only when one behavior is safe and broadly appropriate.
- Use object types for related settings; this prevents a long, loosely related list of variables.
- Add validation for critical guardrails, such as allowed instance sizes, required availability zones, and CIDR shape.
- Mark sensitive inputs with
sensitive = true. Remember that this redacts CLI output; it does not make an unsafe storage location safe.
Outputs: useful, but not leaky
Export values callers need to connect components: IDs, ARNs, DNS names, and endpoint addresses. Do not expose every internal resource simply because Terraform can. Excessive outputs couple callers to internals and turn a refactor into a breaking change.
For example, an ALB module might return dns_name, zone_id, and target_group_arn. A caller rarely needs the individual listener resource IDs.
Version the contract
Once a module is used across teams, publish it from a Git repository or private module registry and pin a released version. For a Git source, pin a tag with ref:
module "network" {
source = "git::https://github.com/acme/terraform-aws-network.git?ref=v2.3.1"
# module inputs
}
For a registry source, use the version argument instead (version = "2.3.1"). Terraform only honours version for registry modules; on a Git source it has no effect.
Treat an input rename, output removal, or semantic behavior change as a versioned API change. Use semantic versioning and a changelog. Do not point production at a branch name such as main; it makes a previously reviewed plan impossible to reproduce later.
8. Separate environments without copying infrastructure code
The dev and prod roots can call the same module version while supplying different values:
# environments/dev/terraform.tfvars
environment = "dev"
aws_region = "eu-west-1"
application_name = "orders"
container_image = "123456789012.dkr.ecr.eu-west-1.amazonaws.com/orders:2026.10.12"
container_port = 8080
# environments/prod/terraform.tfvars
environment = "prod"
aws_region = "eu-west-1"
application_name = "orders"
container_image = "123456789012.dkr.ecr.eu-west-1.amazonaws.com/orders:2026.10.12"
container_port = 8080
Real differences should be explicit in code: production may use more AZs, larger task capacity, stricter deletion protection, longer log retention, and a different deployment role. Do not hide these behind a generic is_production boolean that makes a module behave in several unrelated ways. Prefer named, focused inputs such as enable_deletion_protection or desired_count.
Terraform workspaces can be useful for temporary or highly uniform copies. They are usually a poor boundary for long-lived environments with different permissions, backend access, lifecycle expectations, or approval flows. Separate environment roots and state keys make those boundaries clear.
9. Choose state boundaries deliberately
There is no universal number of state files. Use the smallest boundary that keeps plans reviewable and access appropriately scoped.
Start with one state per environment for a small application. Split it when a part has a distinct lifecycle or ownership model:
prod/
├── network/ # long-lived, cautiously changed
├── shared-data/ # databases, DNS zones, shared secrets policy
└── application/ # fast-moving ECS, ALB rules, task definitions
When separate states must communicate, prefer a stable published contract: a small remote-state output, an AWS data source, or a service-discovery record. Document the producer, consumer, and allowed change process. Avoid chains where a dozen state files read each other’s internal outputs; that recreates a distributed monolith.
Do not split state merely to make files shorter. More state files mean more deployment order, credentials, pipelines, and interfaces to maintain.
10. Build security into the module design
Use Terraform to make the secure path the easy path:
- Keep application workloads in private subnets; expose only a public load balancer when necessary.
- Reference a source security group for service-to-service access instead of broad CIDR ranges.
- Use least-privilege IAM roles per workload and deployment pipeline.
- Store runtime secrets in AWS Secrets Manager or SSM Parameter Store and pass references, not secret values, through Terraform where possible.
- Enable encryption for state, databases, storage, and logs according to your organization’s policy.
- Add default tags so ownership and cost allocation are never optional.
- Protect critical resources with focused lifecycle controls and AWS-side deletion protection where appropriate. Use
prevent_destroysparingly and intentionally; it can also make an emergency migration harder.
Run security and policy checks in CI before apply. Whether you use native Terraform checks, OPA, Sentinel, or another policy engine, keep the policy close to the risk it mitigates: for example, reject an internet-open database security group rather than writing a broad rule that rejects all ingress.
11. Establish a safe delivery workflow
A modular architecture needs a workflow that preserves the benefits of its boundaries.
- Format and validate each changed root or module with
terraform fmt -checkandterraform validate. - Run module tests for behavior that can be asserted without deploying a full environment. Terraform supports native test files for module testing.
- Generate a plan in CI using the target environment’s assumed role.
- Review the plan as a change record, paying particular attention to replacements and destroys.
- Apply the approved, saved plan from a controlled pipeline identity.
- Promote a tested module version or immutable image tag from development to production; do not rebuild it during promotion.
CI should authenticate with short-lived credentials through OIDC or an equivalent federation mechanism. Give the development pipeline no permission to modify production, and keep manual emergency access auditable.
12. Common anti-patterns and better alternatives
| Anti-pattern | Why it hurts | Better approach |
|---|---|---|
| Copying a full environment folder | Fixes and guardrails drift. | Compose the same versioned modules with different inputs. |
| A single 5,000-line root module | Every change has a wide review and state blast radius. | Extract cohesive, reusable capabilities. |
| One module per AWS resource | The configuration becomes an opaque wrapper graph. | Group resources that implement one capability. |
| Deep module nesting | Dependencies and ownership are hidden. | Keep the tree shallow and compose modules in the root. |
| Using names to discover resources created elsewhere | Names collide and create implicit coupling. | Pass IDs/ARNs through module outputs or use a documented data-source contract. |
terraform apply from a workstation in production | Credentials, tool versions, and audit trail vary. | Apply reviewed plans from a controlled CI identity. |
| Unpinned providers and modules | The same code can produce different infrastructure later. | Constrain versions and commit the lock file. |
Secrets in .tfvars | Secrets leak into state and source-control history. | Store secrets in a secrets service and pass references. |
A practical adoption path
You do not need to modularize everything at once. A low-risk migration sequence is:
- Inventory the existing configuration and identify the repeated network, security, and compute patterns.
- Extract one well-understood capability, usually networking, into a module with documented inputs and outputs.
- Replace one environment root with a call to that module, and compare the plan carefully to ensure no resources are recreated unexpectedly.
- Extract the next capability only after the first interface has proven useful.
- Introduce a remote backend and a CI plan/apply workflow if they are not already in place.
- Publish stable module versions once two or more consumers need the same capability.
Use moved blocks and import-aware migration steps when refactoring existing resources. The goal is to change Terraform addresses while retaining the real AWS objects, not to replace production infrastructure because files moved.
Final design checklist
Before calling the architecture complete, verify that:
- Each module represents a coherent capability and has a documented public interface.
- Root modules compose peer modules through explicit inputs and outputs.
- Development and production have separate state keys, credentials, and approval paths.
- State is versioned, encrypted, locked, and reachable only by intended roles.
- Provider and module versions are constrained, and the dependency lock file is committed.
- Security defaults are enforced in code and checked in CI.
- A production plan is small enough for a reviewer to understand its effects.
- Module releases are versioned, tested, and promoted deliberately.
Conclusion
Modular Terraform is not primarily about creating more folders. It is about encoding infrastructure capabilities behind clear contracts, then composing those capabilities where deployment decisions belong. For AWS teams, that separation turns infrastructure code from a collection of environment copies into a platform: consistent where it should be consistent, flexible where applications differ, and safe enough to change with confidence.