So when starting to work with Terraform you very quickly learn about the idea of Modules. These can be fantastic things for wrapping complex operations you want to complete multiple times together. The problem is that you can almost go too far in on creating Modules. So let’s dig into some considerations of things before wrapping that in a module block and deploying it.
Terraform Modules are like a function. They can allow you to do the exact same thing over and over again with a slight change of inputs. This certainly has the benefit of not having a bunch of duplicated code everywhere however it can be bad if you don’t have good variables. Ultimately this can allow it to be as opinionated or as general as someone wants.
One of the main benefits of Modules is the ability to version things. This really allows for upgrading parts of your infrastructure in pieces rather than having to do everything all at once. It can also allow seeing how far behind specific parts of the infrastructure are.
The problem with this is that each version can become a different opinionation. So what is presented as five different versions should really be five different modules completely. This can present a problem since people will be operating on things in completely different ways. This causes splices and some major issues with maintainability.
So one of the biggest problems with modules is when you start setting provider versions. You can end up in a situation where none of the versions match up and everything fails to initialize. This can be frustrating especially when trying to use multiple different modules and none of them are working together well.
When To vs When Not To
So the big question. When would you use this vs. when would you not? The biggest time to begin using this is whenever you need some strong opinions. They are super valuable in this moment and I have found they are super helpful as a bootstrap setup for customers.
They are also helpful whenever you can plan something very specifically. If there are a ton of variables and a ton of differences and you end up writing a bunch of
if blocks then they lose their value.
There is no right answer. The right answer for me may be the wrong answer for you and vice versa. Modules are meant to provide repeatability in my opinion. Rather than spending forever trying to plan them out. Use Terraform to the fullest and then refactor. Sometimes this is easier said than done, but frankly, to me it is better to quickly build up a dev environment, and then rebuild, and then rebuild, and then rebuild, and plan things out that way.