
What are the five best practices I always come back to when I write my own Terraform code, or when I help engineers and organizations write theirs? Most of them are common sense. Here they are.
for_each over count.locals as a configuration store.I have found a lot of times in my career - not just with Terraform - that folks tend to overcomplicate their solution prematurely. I have been known to do this myself from time to time. One common mistake I see made with over-complication is the excessive use of abstraction, such as creating a module that simply wraps an existing Terraform resource. We are now creating a layer on top of that resource that provides little to no value at all. My rule of thumb is if the thing isn't going to be repeated at least five times, I am probably not going to abstract it. This is a very personal number but it does give a decent starting mark.
When you're writing Terraform, think to yourself: is what I am writing simple, clear, and understandable? If it is, then you're on your way to having some good code for others to consume!
for_each > countThe count expression is dead, long live for_each. Since I picked up for_each I have never looked back. It gives me far more control over the code. I can provision many instances or none at all, run logic checks on the inputs before anything gets created, and even build things differently depending on those inputs. Try doing that with a count!
When you write Terraform modules, aim to build ones that capture a pattern. Organizations tend to have set patterns for their services. A database, a backend server, a front-end server, that kind of thing. Whatever gets repeated across the organization is a good candidate for a module.
locals as a configuration storeOften folks store their entire Terraform input configuration inside a locals block, and to some extent it makes sense. In that scenario you're technically not hard-coding values in the Terraform code itself, but the configuration is still stored alongside it in a very static manner. Instead, change your mindset: think of locals as where your global variables or computed properties live. When you think of them in that way, they actually become a really powerful part of your Terraform code and not a place of confusion.
If you're reading your own code and even for a second think you might forget why, how or what COMMENT it!!! I so often see complex for expressions or lots of explicit dependencies or even complex computed properties in a locals block and it is not always obvious why, a simple comment would make the reason for that complexity crystal clear not only to you but to others alongside and after you! Please take the time to write comments, I would even err on the side of caution and comment more rather than less.
Sign up and get started using these in your free account with Scalr.
