Skip to main content
Terraform beginner Lesson 6 of 11

Terraform Modules (reuse, composition, and clean structure)

Learn how Terraform modules package reusable infrastructure patterns. Includes practical module call + outputs example.

Modules let you turn a folder of Terraform code into a reusable component.

Learning outcomes

By the end you’ll be able to:

  • understand what a module is
  • call a module from a root configuration
  • pass variables into modules
  • consume module outputs

1) What is a Terraform module?

A module is a directory containing Terraform configuration.

Common usage:

  • source = "./modules/<name>" for local modules
  • source = "registry.terraform.io/<namespace>/<provider>/<name>" for published modules

2) Local module example (VPC-like pattern)

Project structure:

./main.tf
./variables.tf
./outputs.tf
./modules/vpc/main.tf
./modules/vpc/variables.tf
./modules/vpc/outputs.tf

Root module: main.tf

module "vpc" {
  source = "./modules/vpc"

  cidr_block = "10.0.0.0/16"
  tags = {
    owner = "platform"
    env   = var.environment
  }
}

output "vpc_id" {
  value = module.vpc.vpc_id
}

Root variables.tf

variable "environment" {
  type    = string
  default = "dev"
}

3) Module implementation

modules/vpc/variables.tf

variable "cidr_block" {
  type = string
}

variable "tags" {
  type = map(string)
}

modules/vpc/main.tf

This is a simplified placeholder. Real VPC modules manage subnets, routes, NAT/IGW, etc.

# Example “resource” to demonstrate module structure.
# Replace with real provider resources if you want to run it.

resource "null_resource" "vpc" {
  triggers = {
    cidr = var.cidr_block
  }
}

modules/vpc/outputs.tf

output "vpc_id" {
  value = "vpc-${var.cidr_block}"
}

4) Why modules should be designed well

Good module design:

  • has clear inputs (variables)
  • exposes only the outputs consumers need
  • avoids hiding important configuration behind confusing magic

5) Module versioning and registry (concept)

When using modules from the Terraform Registry, you pin versions:

module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "~> 5.0"

  name = var.project_name
  cidr = var.cidr_block
}

6) When to split into modules

Use modules when:

  • you repeat the same patterns across multiple stacks/environments
  • you want consistent naming/outputs across teams
  • you want to encapsulate complexity

7) Cleanup reminder

Modules don’t change lifecycle rules: terraform destroy destroys based on state and configuration.

Frequently Asked Questions

Why use modules instead of copying code?
Modules improve reuse, enforce consistency, and reduce errors by centralizing common patterns.