Day 11 - Terraform Modules Explained: How to Reuse and Organize Your Infrastructure

Tech-driven, cloud-focused, and growth-minded ☁️ Building skills in cloud engineering with a DevOps base. Passionate about learning and solving real problems.
Introduction
Welcome to Day 11 of my Terraform learning journey! 🎉
So far, we’ve been writing Terraform code in a single main.tf file. That works for small setups, but as infrastructure grows, managing everything in one place becomes messy.
This is where Terraform Modules come in.
🔹 What is a Terraform Module?
A module in Terraform is just a collection of .tf files in a folder.
Think of it as a reusable building block for infrastructure.
For example:
A module to create an EC2 instance
A module to create a VPC
A module to set up an S3 bucket
Instead of writing the same code multiple times, you define it once inside a module and reuse it.
🔹 Types of Modules
Root Module – The main code in your working directory (where you run
terraform apply).Child Module – Any module called by the root or another module.
Public Modules – Pre-built modules from the Terraform Registry.
🔹 Using a Module (Example)
Let’s say you want to launch an EC2 instance using a module:
module "ec2_server" {
source = "./modules/ec2"
instance_type = "t2.micro"
ami = "ami-0144277607031eca2"
server_name = "Day11-Server"
}
Here:
source = "./modules/ec2"→ points to the folder containing the EC2 module.Inputs (
instance_type,ami,server_name) → customize the module.
🔹 Inside the EC2 Module (./modules/ec2/main.tf)
variable "instance_type" {}
variable "ami" {}
variable "server_name" {}
resource "aws_instance" "this" {
ami = var.ami
instance_type = var.instance_type
tags = {
Name = var.server_name
}
}
output "instance_id" {
value = aws_instance.this.id
}
Now you can reuse this EC2 module as many times as you want.
🔹 Why Use Modules?
✅ Reusability – Write once, use many times
✅ Organization – Separate big projects into smaller components
✅ Collaboration – Teams can build and share modules
✅ Consistency – Fewer mistakes by standardizing patterns
🔹 Module Best Practices
Keep modules focused (one responsibility, e.g., “EC2” or “S3”).
Use input variables for flexibility.
Use outputs to expose useful information.
Store common modules in a separate repo for reuse across projects.
Prefer Terraform Registry for well-tested modules (instead of reinventing the wheel).
🔹 Real-World Example
Let’s say you want:
1 VPC (module: vpc)
2 EC2 instances (module: ec2)
1 S3 bucket (module: s3)
Instead of writing everything in one file, you organize them into modules and just call them in your root module.
This makes infrastructure scalable, readable, and reusable.
🔹 Conclusion
Terraform Modules are like Lego blocks for infrastructure 🧩.
They make your code:
Easier to manage
Easier to reuse
Easier to share
From now on, I’ll start modularizing my Terraform projects instead of writing giant main.tf files.
That’s it for Day 11 – Modules 🚀.




