Practical Terraform: You’re Doing it Wrong (Part 1) | by Zachary King | Oct, 2024

Pro-Tip: You can also read this post on the MakeWithData Substack for free!
https://makewithdata.substack.com/p/practical-terraform-youre-doing-it

We’ve all written Terraform IaC that we’re not proud of before — it happens. I’m here today to talk about the Terraform you write that you think you’re proud of…until it outgrows your team, becomes hard to manage, and terrifies you anytime you terraform apply.

1. Monolithic Modules

Terraform modules are a set of reusable code, similar to a class in object-oriented programming. I like to say that the module is the “cookie cutter”; anytime you use it, you are “instantiating” it.

When you create a module, try to keep it short and sweet. Users of your module don’t want to worry about a heap of baggage, like 50+ variables, 4+ providers, and 100+ direct resources, spat out in the first plan.

Take this module for a web application, for example:

webapp_bad
├── api_gateway.tf
├── cloudfront.tf
├── cloudwatch.tf
├── cognito.tf
├── iam.tf
├── lambda.tf
├── load_balancer.tf
├── outputs.tf
├── postgres.tf
├── providers.tf
├── variables.tf
└── vpc.tf

This is a typical stack for a web application on AWS, but I’ll let your imagination fill in the myriad of…