Terraform · Lesson 6 of 12 · 3 min read
Modules
What a module is
Any directory of .tf files is a module. The directory you run Terraform in is the root module; it calls child modules:
modules/
vpc/
main.tf variables.tf outputs.tf versions.tf README.md
envs/
prod/
main.tf backend.tf prod.tfvars
module "vpc" {
source = "../../modules/vpc" # local path
name = "acme-prod"
cidr = "10.20.0.0/16"
azs = ["ap-south-1a", "ap-south-1b", "ap-south-1c"]
}
module "eks_vpc" {
source = "terraform-aws-modules/vpc/aws" # public registry
version = "~> 6.0" # always pin registry modules
# ...
}
module "service" {
source = "git::https://github.com/acme/tf-modules.git//ecs-service?ref=v1.4.0" # Git, pinned by tag
}
output "private_subnet_ids" { value = module.vpc.private_subnet_ids }
- Inputs are the module's
variableblocks; outputs are itsoutputblocks — a module can only see what you pass in. - Modules can use
count/for_each(Terraform 0.13+) to create several instances. - Pass non-default providers explicitly:
providers = { aws = aws.us_east_1 }.
Enlarge diagram
Swipe sideways to see all of it, or tap to open it full screen.
Module design best practices
- Small and focused (a VPC, an EKS cluster, a service), composed in the root — not one giant "everything" module.
- Clear interface: typed variables with descriptions, validation blocks and sensible defaults; outputs for everything callers might need.
- No hardcoded providers or backends inside reusable modules.
- Versioned releases (Git tags, semantic versioning, changelog) — consumers pin versions.
- Examples and tests:
examples/directories,terraform test(1.6+) or Terratest. - Prefer well-maintained community modules (
terraform-aws-modules/vpc,/eks,/iam,/rds) over writing everything — but read what they create.