You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Modules are the primary way to organise, reuse, and share Terraform configuration. A module is simply a directory containing .tf files. This lesson covers creating modules, using module sources, the Terraform Registry, and module composition patterns.
Every Terraform configuration is a module:
terraform applymodule blockproject/
├── main.tf ← root module
├── variables.tf
├── outputs.tf
└── modules/
└── network/ ← child module
├── main.tf
├── variables.tf
└── outputs.tf
| Benefit | Description |
|---|---|
| Reusability | Write once, use across multiple projects |
| Organisation | Group related resources into logical units |
| Encapsulation | Hide implementation details behind a clean interface |
| Consistency | Enforce standards across your organisation |
| Testability | Test modules independently |
A module has the same file structure as any Terraform configuration:
modules/network/
├── main.tf # Resources
├── variables.tf # Input variables (the module's interface)
├── outputs.tf # Output values (what the module exposes)
└── README.md # Documentation
modules/network/variables.tf:
variable "vpc_cidr" {
description = "CIDR block for the VPC"
type = string
default = "10.0.0.0/16"
}
variable "environment" {
description = "Environment name"
type = string
}
modules/network/main.tf:
resource "aws_vpc" "main" {
cidr_block = var.vpc_cidr
enable_dns_hostnames = true
tags = { Name = "${var.environment}-vpc" }
}
resource "aws_subnet" "public" {
vpc_id = aws_vpc.main.id
cidr_block = cidrsubnet(var.vpc_cidr, 8, 1)
map_public_ip_on_launch = true
tags = { Name = "${var.environment}-public" }
}
modules/network/outputs.tf:
output "vpc_id" {
description = "The ID of the VPC"
value = aws_vpc.main.id
}
output "public_subnet_id" {
description = "The ID of the public subnet"
value = aws_subnet.public.id
}
Use a module block to call a child module:
module "network" {
source = "./modules/network"
vpc_cidr = "10.0.0.0/16"
environment = "production"
}
resource "aws_instance" "web" {
ami = data.aws_ami.ubuntu.id
instance_type = "t3.micro"
subnet_id = module.network.public_subnet_id
}
After adding or changing a module source, run:
terraform init
Terraform supports many module sources:
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.