Module Composition Patterns
What you'll learn: How to build complex infrastructure by layering and combining multiple Terraform modules together.
The Core Idea
Just like building with LEGO blocks, you can compose sophisticated infrastructure by connecting multiple smaller, focused modules. Module composition means structuring your Terraform code so specialized modules work together to create complete systems—rather than building everything in one giant configuration.
Why Compose Modules
A single module might create a VPC, another handles an application tier, and a third manages a database. Instead of cramming all this logic into one place, you compose them: your root module calls each child module, passing outputs from one as inputs to another.
Common Composition Patterns
Layered Architecture
Stack modules in logical layers: networking → security → compute → application. Each layer's outputs feed the next layer's inputs.
module "network" {
source = "./modules/vpc"
cidr = "10.0.0.0/16"
}
module "security" {
source = "./modules/security-groups"
vpc_id = module.network.vpc_id
}
module "app" {
source = "./modules/web-app"
subnet_ids = module.network.private_subnet_ids
security_group = module.security.app_sg_id
}
Wrapper Modules
Create a high-level module that internally calls multiple child modules, exposing only essential inputs and outputs. This hides complexity from users.
Environment-Specific Composition
Use the same modules with different variable values for dev, staging, and production—composition stays consistent, configuration varies.
Key Takeaway: Module composition patterns let you build complex, maintainable infrastructure by combining focused, reusable modules in layered or wrapped architectures—making your code cleaner and more scalable.