Terraform is powerful, but without modularization, your infrastructure can quickly become a tangled mess. If you've ever found yourself copy-pasting code between projects or dreading updates across multiple environments, it's time to go modular.
Here’s a quick guide to Terraform modules—the right way. ⬇️
1️⃣ Stop Repeating Yourself (DRY Principle)
Ever duplicated the same VPC or EKS setup across multiple projects? That’s a sign you need modules. Instead of copying .tf
files, encapsulate repeatable infrastructure into reusable modules that you can call with different inputs.
📌 Example:
module "network" {
source = "./modules/network"
vpc_cidr = "10.0.0.0/16"
}
✅ One module, multiple uses.
2️⃣ Group Related Resources Together
The biggest mistake? Breaking things into too many micro-modules.
Instead of a separate module for every tiny resource, group related resources logically.
✅ Good module structure:
✔ Compute Module → EKS, Node Pools, Autoscaling
✔ Network Module → VPC, Subnets, Security Groups
✔ Storage Module → S3 Buckets, EBS Volumes
❌ Bad practice: A separate module for every IAM role, security group, or subnet. That’s over-modularization and makes things harder to maintain.
3️⃣ Use outputs.tf
to Pass Data Between Modules
Terraform modules don’t work in isolation—they should pass information seamlessly. Use outputs.tf
to expose critical values from one module to another.
📌 Example:
output "vpc_id" {
value = aws_vpc.main.id
}
Now, another module can reference this output instead of hardcoding values.
4️⃣ Keep Your Modules Configurable with variables.tf
Hardcoded values kill reusability. Use variables.tf
to make your modules flexible across environments.
📌 Example:
variable "instance_type" {
type = string
default = "t3.medium"
}
Now, you can override it per deployment instead of editing module code.
5️⃣ Call Modules from Your Root Module
Once your modules are set up, your root module should look simple and clean.
Instead of defining all resources, it should just reference modules with input variables.
📌 Example:
module "eks" {
source = "./modules/compute"
cluster_name = "my-cluster"
}
✅ Scalable. Reusable. Maintainable.
🚀 Ready for the Full Breakdown?
This is just a 5-minute crash course on modular Terraform. If you want a deep dive into structuring your infrastructure the right way, check out my full guide:
🔗 Read the full blog post here
What’s Your Take?
💬 How do you approach Terraform modularization? Have you run into challenges or best practices worth sharing? Let’s discuss in the comments!
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.