Terraform modules
What're terraform modules?
Module is an abstraction for multiple resources which can be reused.
Let's say we define our website service with the following layers in AWS:
- s3 for static resources (html, css, js, images, etc.)
- cloudfront for cdn
- application load balancer for receiving backend calls
- Target group with autoscaling group behind application load balancer.
- ec2 instances behind target group.
- RDS mysql for database hosting.
- Appropriate security group and other networking layers.
If we write all resources in terraform generally, we'll create a bunch of resources.
After a few days, we've decided the same tech stack is needed for 4 more websites. Now, we've to copy paste the code of all the resources and have different resource names like rds-website-2, rds-website-3, etc.
What if we want to abstract it all and give a way to just let website owner define variables and launch infrastructure layers?
We put a generic structure of all the resources mentioned above in a folder called modules. Let's call our module as website_infra
Thus, a new website can be launched simply by using:
module 'website_infra' {
name_of_website = "acsrujan.net"
s3_bucket_name = "acsrujan"
ssl_enabled = true
}
And rest everything is handled by the module. We can give finer controls in the module definition and flags like if cdn is needed or not, etc.
How to write a module?
The best examples are in open source. Here's something one can begin with: