Modules: Reusable Infrastructure Components
7 min read
Course: Terraform
Topic: Modules: Reusable Infrastructure Components
π Welcome to the Industrial Revolution of Infrastructure!
If you made it this far, you know how to create resources. You are likely feeling powerful. You can spin up an EC2 instance with a few lines of code. But let's be honest for a second: if you had to create 50 identical servers for 50 different environments, would you copy-paste that code block 50 times?
If you answered "Yes," please stop. We care about your sanity. π§
Today we are tackling Modules. This is the moment you graduate from "I can write a script" to "I can architect a scalable system."
1. Introduction to Modules: Don't Repeat Yourself (DRY) ποΈ
The Problem: The "Wall of Text"
Imagine you are building a house. You need a window. You describe the glass, the frame, the handle, and the screws. Now you need another window. Do you describe the glass, frame, handle, and screws again?
In coding, copying and pasting resource blocks leads to massive files (main.tf with 2,000 lines) that are impossible to read, hard to debug, and terrifying to update.
The Concept: What is a Module?
A Module in Terraform is simply a container for multiple resources that are used together. A module consists of a collection of .tf files kept together in a directory.
Technical Definition: A module is a self-contained package of Terraform configurations that encapsulates a specific set of infrastructure resources to provide a reusable abstraction.
π‘ Interesting Fact: technically, you have already been using modules. The directory where you run
terraform applyis called the Root Module. Any module called by the root module is a Child Module.
How it Solves the Problem
Instead of defining the "Window" details 50 times, you define the "Window" once in a separate folder. Then, in your main file, you just say: "Give me a Window here, here, and here."
If you need to change the glass type, you change it in one place, and all 50 windows update automatically. This adheres to the DRY (Don't Repeat Yourself) principle.
2. Consuming Public Modules from the Terraform Registry π
The Problem: Reinventing the Wheel
Let's say you want to build an AWS VPC (Virtual Private Cloud). You need a VPC resource, public subnets, private subnets, internet gateways, route tables, route table associations, and NAT gateways.
Writing that from scratch takes hours and is prone to errors (e.g., forgetting to associate a route table). Why suffer when thousands of engineers have already solved this?
The Solution: The Terraform Registry
The Terraform Registry is a public repository of modules written by the community and official providers (like AWS, Google, Azure).
How to use it
To use a module, you use the module block instead of a resource block.
Scenario: We need a VPC. Instead of writing 15 resource blocks, we use the official AWS VPC module.
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "5.0.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
}π Explanation:
module "vpc": This gives the module instance a local name ("vpc").source: The most important line. It tells Terraform where to download the code. This address points to the public registry.version: CRITICAL INDUSTRY PRACTICE. Always pin your version. If you don't, Terraform downloads the latest. If the author releases a breaking change tomorrow, your production pipeline might explode.- Arguments:
name,cidr, etc., are input variables defined by the module author.
β‘ Action Step: The init Command
When you add a module, your local Terraform doesn't have the code for it yet. You must run:
terraform initThis downloads the module files into a hidden .terraform/modules directory.
3. Creating Your First Custom Local Module π¦
The Problem: Company Standards
The public registry is great for generic things (VPCs, K8s clusters), but what about your company's specific needs?
- "Every S3 bucket must have encryption enabled."
- "Every web server must have these specific tags."
You can't find a "MyCompany-Specific-Bucket" on the public registry.
The Solution: Local Modules
You create a folder on your computer, put .tf files in it, and reference it using a relative path.
Industry Standard Structure
A clean Terraform project usually looks like this:
my-project/
βββ main.tf (Root Module)
βββ modules/ (Folder for custom modules)
β βββ web-server/ (Child Module)
β βββ main.tf
β βββ variables.tf
β βββ outputs.tfStep-by-Step Simulation
Step A: Define the Child Module
Inside modules/web-server/main.tf, we define a simple Nginx server.
# modules/web-server/main.tf
resource "aws_instance" "app_server" {
ami = "ami-0c55b159cbfafe1f0" # Amazon Linux 2 (Example)
instance_type = "t2.micro"
tags = {
Name = "Standard-Web-Server"
Role = "Production"
}
}Step B: Call it from the Root
Inside your root main.tf:
# main.tf
module "marketing_server" {
source = "./modules/web-server"
}
module "finance_server" {
source = "./modules/web-server"
}Result: You just created two identical servers with standardized tags by writing the resource logic only once!
4. Passing Inputs and Extracting Outputs ποΈ
The Problem: Hardcoded Modules are Useless
Look at the example above. Both servers are t2.micro and have the exact same AMI. What if Marketing needs a bigger server? What if we need to know the IP address of the Finance server to put it in a DNS record?
A module without inputs is like a calculator that only adds 2 + 2. We need it to add X + Y.
The Solution: Variables and Outputs
Think of a module like a Function in programming:
- Variables = Function Arguments (Input)
- Resources = Function Logic (Body)
- Outputs = Return Values (Output)
Practical Implementation
Let's refactor our web-server module to be dynamic.
1. The Inputs (variables.tf inside the module)
We define what the module accepts.
# modules/web-server/variables.tf
variable "server_size" {
description = "The EC2 instance type"
type = string
default = "t2.micro" # Fallback if not specified
}
variable "app_name" {
description = "Name of the application"
type = string
}2. The Logic (main.tf inside the module)
Update the resource to use these variables.
# modules/web-server/main.tf
resource "aws_instance" "app_server" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = var.server_size # Dynamic size!
tags = {
Name = var.app_name # Dynamic name!
Role = "Production"
}
}3. The Return Values (outputs.tf inside the module)
We define what the module sends back to the root. By default, child module data is hidden (encapsulated). You must explicitly expose it.
# modules/web-server/outputs.tf
output "instance_ip_addr" {
value = aws_instance.app_server.public_ip
description = "The public IP of the web server"
}
output "instance_id" {
value = aws_instance.app_server.id
}4. The Usage (Root main.tf)
Now we pass values in and access values out.
# main.tf
# 1. Calling the module with inputs
module "marketing_server" {
source = "./modules/web-server"
server_size = "t3.large" # Marketing needs power!
app_name = "Marketing-App"
}
# 2. Using the module's output
resource "aws_eip" "lb" {
domain = "vpc"
# We access the output using: module.<module_name>.<output_name>
instance = module.marketing_server.instance_id
}π¨ Industry Best Practices (Read this or suffer)
- Pin Versions: When using Public Registry modules, always specify
version = "x.y.z". Updates can break your infrastructure. - Relative Paths: When using local modules, start the source path with
./or../. - Encapsulation: Don't expose everything. Only create variables for things users need to change, and only output values other resources need to consume.
- No Providers in Modules: Generally, do not define
provider "aws" {...}inside a child module. Let the root module handle authentication. Child modules inherit providers automatically.
π References & Further Reading
Summary: Modules turn your messy "Spaghetti Code" into clean, reusable "Lego Blocks." Use the Registry for standard infrastructure (VPC, RDS), and write Local Modules for your company's specific patterns. Now, go refactor your code! π§Ήβ¨
Challenge
Challenge: Create and Use a Local Terraform Module
Your task is to build a reusable local Terraform module for deploying a standardized S3 bucket configured for static website hosting. You will then call this module from your root main.tf file.
Simulate the following directory structure within the single editor window using comments as file dividers.
my-project/
βββ main.tf
βββ modules/
βββ s3_static_site/
βββ main.tf
βββ variables.tf
βββ outputs.tfModule (s3_static_site) Requirements:
Inputs (
variables.tf): The module must accept two input variables:bucket_name: A variable of typestringfor the S3 bucket's unique name.tags: A variable of typemap(string)to apply common tags to the bucket.
Resources (
main.tf): The module must define the following AWS resources:- An
aws_s3_bucketresource that uses thebucket_nameandtagsinput variables. - An
aws_s3_bucket_website_configurationresource associated with the bucket, configuringindex_documenttoindex.html. - An
aws_s3_bucket_public_access_blockresource that setsblock_public_aclsandblock_public_policytofalse, andignore_public_aclsandrestrict_public_bucketstofalseto allow public access for the website.
- An
Outputs (
outputs.tf): The module must expose two values:bucket_arn: The ARN of the created S3 bucket.website_endpoint: The website endpoint of the S3 bucket.
Root Module (main.tf) Requirements:
- Define a
moduleblock with the local namepersonal_blog. - Use the correct relative
sourcepath to reference your locals3_static_sitemodule. - Pass the following values to the module:
bucket_name:my-unique-static-blog-buckettags: A map containing{"ManagedBy" = "Terraform", "Project" = "Blog"}
Expected result
Your final code should be structured into the four commented sections provided in the initial code.
modules/s3_static_site/variables.tf: This section should contain twovariableblocks, one forbucket_nameand one fortags, each defined with the correcttype.modules/s3_static_site/main.tf: This section should contain three resource blocks:aws_s3_bucket,aws_s3_bucket_website_configuration, andaws_s3_bucket_public_access_block. The resource attributes should correctly reference the input variables (e.g.,var.bucket_name).modules/s3_static_site/outputs.tf: This section should contain twooutputblocks forbucket_arnandwebsite_endpoint. Theirvalueattributes should reference the appropriate attributes from the resources created in the module'smain.tf.main.tf(Root Module): This section must contain a singlemodule "personal_blog"block. Thesourceattribute must be the correct relative path ("./modules/s3_static_site"). The block must pass the specifiedbucket_namestring andtagsmap as arguments.