DEV Community

Mary Mutua
Mary Mutua

Posted on

Building Reusable Infrastructure with Terraform Modules

Day 8 of my Terraform journey focused on one of Terraform’s most important ideas: modules.

After a week of building infrastructure, I started noticing the same patterns repeating:

  • security groups
  • launch templates
  • Auto Scaling Groups
  • Application Load Balancers
  • listeners
  • target groups

So today I stopped copying that logic and turned it into a reusable Terraform module.

Why Modules Matter

A module is a reusable package of Terraform code.

Instead of rewriting the same infrastructure for every environment, you write it once and call it from different root configurations with different inputs.

That gives you:

  • less duplication
  • cleaner code
  • easier maintenance
  • more consistency across environments

Module Structure

I organized my module like this:

modules/
└── services/
    └── webserver-cluster/
        ├── main.tf
        ├── variables.tf
        ├── outputs.tf
        └── README.md

Enter fullscreen mode Exit fullscreen mode

This module packages a reusable web server cluster made of:

  • an ALB
  • a target group
  • a listener
  • security groups
  • a launch template
  • an Auto Scaling Group

Inputs and Outputs

To make the module reusable, I moved environment-specific values into inputs such as:

  • cluster_name
  • environment
  • instance_type
  • min_size
  • max_size
  • desired_capacity
  • server_port

I also exposed outputs that a caller would need, including:

  • alb_dns_name
  • asg_name

That means the module hides the repeated infrastructure logic, while still letting the caller configure what matters.

Calling the Module

I then created root configurations that reused the same module with different values.

For example:

  • dev used smaller settings
  • production used larger settings

So the pattern became:

  • same module
  • different inputs
  • zero code duplication

That was the biggest lesson of the day.

What Makes a Good Module

After building one, I think a good Terraform module should be:

  • focused on one job
  • easy to understand
  • configurable where needed
  • not overloaded with too many inputs
  • documented clearly in a README

A painful module is one that:

  • hardcodes too much
  • exposes too many confusing variables
  • has weak outputs
  • has no usage guidance

My Takeaway

Earlier days taught me how to build the infrastructure itself.

Day 8 taught me how to package that infrastructure into something reusable.

That shift feels important. Modules are what make Terraform code easier to scale across environments, projects, and teams.

I kept the full module code and root usage examples in GitHub here:

👉 Github Link

Follow My Journey

This is Day 8 of my 30-Day Terraform Challenge.

See you on Day 9 🚀

Top comments (0)