1. Overview

Previously, we’ve covered Terraform’s basic concepts and usage. Now, let’s dig deeper and cover some of the best practices when using this popular DevOps tool.

2. Resource Files Organization

When we start using Terraform, it’s not uncommon to put every resource definition, variable, and output in a single file. This approach, however, quickly leads to code that is hard to maintain and even harder to reuse.

A better approach is to take benefit from the fact that, within a module, Terraform will read any “.tf” file and process its contents. The order in which we declare resources in those is not relevant – this is Terraform’s job, after all. We should keep them organized so that we can better understand what’s going on.

Here, consistency is more important than how we choose to organize resources in our files. A common practice is to use at least three files per module:

  • variables.tf: All module’s input variables go here, along with their default values when applicable
  • main.tf: This is where we’ll put our resource definitions. Assuming that we’re using the Single Responsibility principle, its size should stay under control
  • _modules: _If our module contains any sub-modules, this is where they’ll go
  • outputs.tf: Exported data items should go here
  • _providers.tf: _Used only on the top-level directory, declares which providers we’ll use in the project, including their versions

This organization allows any team member that wants to use our module to locate which are the required variables and output data quickly.

Also, as our module evolves, we must keep an eye on the main.tf file’s size. A good sign that we should consider refactoring it into sub-modules is when it starts to grow in size. At this point, we should refactor it by moving tightly-coupled resources, such as an EC2 instance and an attached EBS volume, into nested modules. In the end, the chances are that our top-level main.tf file contains only module references stitched together.

3. Modules Usage

Modules are a powerful tool, but, as in any larger software project, it takes some time to get the right level of abstraction so we can maximize reuse across projects. Given the fact that Terraform, as the whole infrastructure-as-code practice, is relatively new, this is an area where we see many different approaches.

That said, we can still reuse some lessons learned from application codebases that can help with proper module organization. Among those lessons, the Single Responsibility from the S.O.L.I.D set of principles is quite useful.

In our context, this means a module should focus on a single aspect of the infrastructure, such as setting up a VPC or creating a virtual machine – and just that.

#cloud #devops #terraform

Best Practices When Using Terraform
1.50 GEEK