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.