Table of Contents
What Are Terraform Modules?
A module is a container for multiple resources that are used together. Every Terraform configuration is technically a module (the root module). Child modules let you organize and reuse infrastructure code.
Using a Module
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "5.1.0"
name = "my-vpc"
cidr = "10.0.0.0/16"
azs = ["us-east-1a", "us-east-1b"]
private_subnets = ["10.0.1.0/24", "10.0.2.0/24"]
public_subnets = ["10.0.101.0/24", "10.0.102.0/24"]
enable_nat_gateway = true
}
Module Sources
# Terraform Registry (recommended)
source = "terraform-aws-modules/vpc/aws"
# GitHub
source = "github.com/org/repo//modules/vpc"
# Local path
source = "./modules/networking"
# S3 bucket
source = "s3::https://bucket.s3.amazonaws.com/modules/vpc.zip"
# Git over SSH
source = "[email protected]:org/repo.git//modules/vpc?ref=v1.0.0"
Creating a Module
Module Structure
modules/networking/
├── main.tf # Resources
├── variables.tf # Input variables
├── outputs.tf # Output values
├── versions.tf # Required providers
└── README.md # Documentation
Example Module
variables.tf:
variable "vpc_cidr" {
type = string
description = "CIDR block for the VPC"
}
variable "environment" {
type = string
description = "Environment name (dev, staging, prod)"
}
main.tf:
resource "aws_vpc" "this" {
cidr_block = var.vpc_cidr
enable_dns_hostnames = true
tags = { Name = "${var.environment}-vpc" }
}
outputs.tf:
output "vpc_id" {
value = aws_vpc.this.id
description = "The ID of the VPC"
}
Module Best Practices
- Keep modules focused — one module per logical component
- Always version modules — use semantic versioning
- Document inputs and outputs — use descriptions on every variable and output
- Don’t hardcode providers — let the caller configure providers
- Use
terraform-docsto auto-generate documentation - Test modules with Terratest or
terraform test
Learn More
- Terraform for Beginners Course — hands-on module labs
- Terraform By Example Book — real-world patterns
- Terraform Cheat Sheet — quick command reference



