Building Reusable Terraform Modules
Learn how to create modular, reusable Terraform configurations that scale across teams and projects.
March 5, 20252 min read
terraformiacdevopscloud
Building Reusable Terraform Modules
Terraform modules are the key to managing infrastructure at scale. They let you encapsulate and reuse configuration, making your IaC codebase maintainable and consistent.
Why Modules?
- Reusability — Write once, use everywhere
- Consistency — Enforce standards across teams
- Abstraction — Hide complexity behind clean interfaces
- Testing — Test infrastructure components in isolation
Module Structure
A well-organized module follows this structure:
modules/
vpc/
main.tf
variables.tf
outputs.tf
README.md
examples/
complete/
main.tf
tests/
vpc_test.go
Example: VPC Module
# modules/vpc/variables.tf
variable "name" {
description = "Name of the VPC"
type = string
}
variable "cidr" {
description = "CIDR block for the VPC"
type = string
default = "10.0.0.0/16"
}
variable "azs" {
description = "Availability zones"
type = list(string)
}
variable "enable_nat_gateway" {
description = "Enable NAT gateway"
type = bool
default = true
}
# modules/vpc/main.tf
resource "aws_vpc" "main" {
cidr_block = var.cidr
enable_dns_hostnames = true
enable_dns_support = true
tags = {
Name = var.name
}
}
resource "aws_subnet" "public" {
count = length(var.azs)
vpc_id = aws_vpc.main.id
cidr_block = cidrsubnet(var.cidr, 8, count.index)
availability_zone = var.azs[count.index]
tags = {
Name = "${var.name}-public-${var.azs[count.index]}"
}
}
Using the Module
module "vpc" {
source = "./modules/vpc"
name = "production"
cidr = "10.0.0.0/16"
azs = ["us-east-1a", "us-east-1b", "us-east-1c"]
enable_nat_gateway = true
}
Best Practices
- Version your modules — Use semantic versioning
- Document inputs and outputs — Use
descriptionfields - Provide examples — Include working examples
- Test your modules — Use Terratest or tftest
- Use remote state — Store state in S3/GCS with locking
Conclusion
Well-designed Terraform modules are the foundation of scalable infrastructure management. Invest time in getting the abstractions right, and your team will move faster with fewer errors.