šŸ› ļø Building Reusable Infrastructure with Terraform Modules

Today in my Terraform journey, I explored the concept of modules — one of the most powerful tools for creating scalable and maintainable infrastructure as code. Modules help organize code, enforce standards, and avoid repetition.

āœ… Why Modules Matter

In real-world cloud infrastructure, repeating the same resource definitions across multiple environments or services becomes messy. Modules solve this by allowing us to define a resource once and reuse it many times. This brings:

🧱 How I Built an EC2 Module

I created a basic EC2 instance module inside modules/ec2-instance that looks like this:

# modules/ec2-instance/main.tf
resource "aws_instance" "ec2" {
  ami           = var.ami
  instance_type = var.instance_type
  tags          = var.tags
}
# modules/ec2-instance/variables.tf
variable "ami" {
  type = string
}
variable "instance_type" {
  type = string
}
variable "tags" {
  type = map(string)
}
# modules/ec2-instance/outputs.tf
output "public_ip" {
  value = aws_instance.ec2.public_ip
}

šŸ” Reusing the Module

I then used the module in my root main.tf file to create an EC2 instance:

# main.tf
provider "aws" {
  region = "us-west-2"
}

module "web_server" {
  source        = "./modules/ec2-instance"
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
  tags = {
    Name        = "Day8WebServer"
    Environment = "dev"
  }
}

output "web_server_ip" {
  value = module.web_server.public_ip
}

With just a few lines, I launched a fully functional, reusable EC2 instance. I can now spin up multiple instances just by changing the inputs!

šŸš€ Conclusion

Terraform modules are a game-changer for clean, scalable infrastructure. This EC2 example is just the beginning — you can use modules for VPCs, databases, load balancers, and more. I’m excited to keep building smarter with reusable infrastructure!