How To Keep Your Terraform Code Clean — The Sustainable Way | by Guillaume Vincent | Apr, 2022

Picture by No Revisions on Unsplash

Working in a DevOps workforce implies contributing to many Terraform repositories. Generally we don’t have all the identical means of writing Terraform code. Code critiques turns into additionally time-consuming and sustaining code is hard.

As you go alongside, you’ll personal increasingly Terraform code and in the future will at all times be 24 hours. Methods to maintain a great high quality stage with the smallest of effort? This time is treasured, you should not waste it.

Right here, automation is your salvation to maintain your Terraform code clear. You’ll be capable of deal with extra code with much less effort. Then, make investments the freed-up time on extra impactful duties.

This text reveals you the primary steps to start out this steady enchancment. This considerations greatest practices and instruments. Terraform has built-in instruments, others are so as to add to your config.

Terraform fmt

Whenever you learn a non-standard code, your eye has to adapt on a regular basis. This requires extra focus to maintain up. You could standardize the code format to make sure good readability.

Terraform gives a built-in subcommand named fmt. It rewrites your code to comply with subsets of the Terraform language style conventions.

$ terraform fmt

💡 Formatting guidelines could change between Terraform variations. Don’t overlook to run terraform fmt command after a model improve.

Naming conference

One of many principal difficulties in laptop science is to call issues effectively. The identical applies to Terraform for variables, outputs, sources, and information sources. And that is the place a great naming conference comes into play.

This can can help you have an unambiguous code. It can learn itself as English.

On this article, I gained’t go into the entire naming conference. Nonetheless, I invite you to seek the advice of this hyperlink which gives an inspiring one:

Terraform validate

Beforehand, you will have seen the fmt command of Terraform. Terraform validate is one other built-in subcommand. It can can help you test and monitor syntax errors and typos.

Let’s take the next instance:

The snippet accommodates an error on the useful resource title. Working validate subcommand on it highlights it:

$ terraform validate

│ Error: Invalid useful resource kind

│ on line 5, in useful resource "aws_instanc" "foo":
│ 5: useful resource "aws_instanc" "foo" {

│ The supplier hashicorp/aws doesn't help useful resource kind
| "aws_instanc". Did you imply "aws_instance"?

Terraform code would possibly look legitimate from the Terraform eyes however in actuality could not work. On this instance, the code declares an inexisting AWS supplier area and a unsuitable occasion kind:

Terraform signifies all is right when working validate:

$ terraform validate
Success! The configuration is legitimate.

It’s because Terraform verifies solely the code syntax and construction. It doesn’t test the values used within the AWS suppliers and sources. That is exterior the Terraform scope and associated to the supplier one.

💡 Think about Terraform validate as step one for fast verification. It doesn’t detect all of the errors earlier than terraform apply.


TFLint is a linter checking potential Terraform errors and implementing greatest practices. You’ll be able to add plugins suitable with main cloud suppliers — AWS, Azure, GCP — for superior error detection. Greatest practices are configurable by means of a rule system.

TFLint appears to be like at all times for extra .tflint.hcl file within the present listing the place it runs. On this configuration file, you add particular guidelines and plugins.

Right here is an instance of TFLint configuration:

  1. The plugin AWS is added to detect particular errors.
  2. A rule to detect invalid AWS occasion sorts is enforced.

Now, let’s take the earlier Terraform AWS code snippet:

You need to initialize TFLint in your terraform listing:

$ tflint --init

Subsequent, run the TFLint with the listing location:

$ tflint .
1 situation(s) discovered:

Error: "unsuitable" is an invalid worth as instance_type (aws_instance_invalid_type)

on line 7:
7: instance_type = "unsuitable"

Terraform is nothing roughly than a device for managing infrastructure as code. It’s as much as you to make sure a great safety design. That is essential to test for misconfiguration that will result in a vulnerability.

What’s Checkov?

Checkov is a static code evaluation device for scanning infrastructure as code information. It helps Terraform and contains greater than 750 predefined insurance policies. You too can contribute and create your customized insurance policies.

Set up Checkov

$ brew set up checkov

Consider the Terraform plan

Create a JSON file from the Terraform plan:

$ terraform init
$ terraform plan --out tfplan.binary
$ terraform present -json tfplan.binary | jq '.' > tfplan.json

Checkov learn this file and returns outputs with suggestions:

The Checkov output of the Terraform plan
The Checkov output of the Terraform plan

What’s pre-commit?

Pre-commit is a framework to handle git hook scripts. They’re helpful for figuring out easy points earlier than submission to code assessment. Earlier than you even kind a commit message, pre-commit hooks are run.

Pre-commit replaces many instructions you kind to test your code.

Set up pre-commit

$ brew set up pre-commit

It’s also potential to put in it with pip:

$ pip set up pre-commit

Methods to use pre-commit?

The Terraform code must be in an initialized git repository. Pre-commit expects a configuration named .pre-commit-config.yaml. On this file, you outline the pre-commit hooks for Terraform.

Initialize the git repository:

$ git init

Right here is the pre-commit configuration:

The pre-commit config makes use of hooks from 2 completely different repositories. The primary is Terraform-specific, and the second is extra generic. It runs terraform fmt, terraform validate, tflint you will have seen earlier than. The order of the hook definition is the execution order.

As soon as the config is prepared, that you must add the Terraform information in git:

$ git add

You’ll be able to run pre-commit manually with this command:

$ pre-commit run -a

Pre-commit has executed all of the hook scripts and up to date the Terraform file. It must re-add the file in git to have in mind the replace. Pre-commit is routinely run when committing the code.

By means of this information, you will have seen the primary factor to get began and maintain your Terraform code clear. This depends on the implementation of fine practices and using instruments like linters and scanners.

With pre-commit, you may automate the checking of potential errors domestically in a single command. The checks are carried out routinely earlier than committing the code to the distant git repository. This can make your code critiques extra environment friendly.

Pre-commit will can help you streamline your CI/CD pipelines. It has many hook scripts to drive many Terraform linters and scanners.

Thanks and I hope this text helped you with Terraform! Wish to be taught extra about DevOps? It’s down under:

More Posts