What is a module?
A module is a collection of Terraform resources grouped for reuse. The folder you run terraform apply in is the root module; anything under modules/ is a child module.
Problem without modules
Project 1 → copy VPC code
Project 2 → copy VPC code
Project 3 → copy VPC code
Duplication grows with every new stack.
Solution
Create module once
↓
Reuse everywhere
Module architecture
Root Module
├── VPC Module
├── EC2 Module
└── S3 Module
Recommended layout
terraform-project/
├── main.tf
├── variables.tf
├── outputs.tf
├── provider.tf
├── terraform.tfvars
└── modules/
├── ec2/
│ ├── main.tf
│ ├── variables.tf
│ └── outputs.tf
├── s3/
│ ├── main.tf
│ ├── variables.tf
│ └── outputs.tf
└── vpc/
├── main.tf
├── variables.tf
└── outputs.tf
Create an EC2 module
modules/ec2/main.tf
resource "aws_instance" "web" {
ami = var.ami
instance_type = var.instance_type
}modules/ec2/variables.tf
variable "ami" {}
variable "instance_type" {}modules/ec2/outputs.tf
output "instance_id" {
value = aws_instance.web.id
}Call the module from the root
main.tf
module "ec2" {
source = "./modules/ec2"
ami = "ami-xxxxxxxx"
instance_type = "t3.micro"
}Use a module output in the root:
output "ec2_id" {
value = module.ec2.instance_id
}After adding or changing a module source, run:
terraform init
terraform plan
terraform applyBenefits
| Benefit | Why it matters |
|---|---|
| Reusable | Share VPC/EC2 patterns across projects |
| Maintainable | Fix once in the module, improve every caller |
| Scalable | Compose larger stacks from small pieces |
Keep modules focused. A “do everything” module is harder to reuse than small VPC, EC2, and S3 modules.