Terraform

What is TFLint and How to Lint Your Terraform Code

What is TFLint

In this article, we will look into ‘linting’, explaining what it is and why you should ‘lint’, before looking at the popular open-source Terraform Linter, TFLint.

You will learn:

  1. What is a Terraform linter?
  2. What is TFLint
  3. .tflint.hcl file
  4. How to install TFLint
  5. How to use TFLint – Example
  6. How to disable TFLint

What is a Terraform linter?

Linting is the process of using a static code analysis tool to identify potential errors, bugs, stylistic errors, and suspicious constructs in your code. The term “lint” comes from the Unix utility lint, which was used to analyze C code for errors. Linting tools are available for use with most coding languages, not just Hashicorp Configuration Language (HCL) used by Terraform.

By using linting tools, development teams can establish a consistent coding style across projects, make the code more readable and understandable, and catch common mistakes that might go unnoticed during manual code reviews. Linting promotes best practices and helps maintain a high level of code quality throughout the development lifecycle.

A Terraform linter is a tool that helps ensure the quality and consistency of Terraform code by analyzing it for potential issues, errors, or violations of best practices.

What is TFLint?

TFLint is a popular open-source linter and static analysis tool designed explicitly for Terraform. It performs automated checks on Terraform configurations to identify potential issues, errors, and violations of best practices. TFLint helps maintain code quality, consistency, and reliability in Terraform projects.

Even though they are mainly static code analysis tools, Other open-source tools like Checkov (that can incidentally also be used with AWS Cloudformation and Kubernetes), and Terrascan can be used for Terraform linting. And you can integrate all of these tools with Spacelift using custom inputs.

Terraform also includes an in-built command terraform fmt formatting tool that helps enforce consistent code style across Terraform configurations. It automatically adjusts the formatting of your code to adhere to the Terraform style conventions, ensuring clean and readable code.

It is not strictly a linter, as its primary function is to format the code, and it doesn’t offer the same level of analysis and rule enforcement that dedicated linters provide.

Another built-in command terraform validate only validates the syntax of your Terraform configurations and is not a linter.

.tflint.hcl file

The .tflint.hcl file is a configuration file used by TFLint that allows you to customize and configure TFLint’s behavior and rules. You can also write this file in .json format, as TFLint also considers any files named .tflint.json .

This file includes the following customization options:

  1. Ruleset selection: Rulesets are predefined sets of rules that focus on specific aspects, such as cloud-specific rules, security rules, or best practice rules. They can be specified in the configuration file and determine which rulesets should be enabled or disabled.
  2. Rule customization: TFLint allows you to customize individual rules. For example, you can change the severity level (e.g., error, warning, info) for specific rules or exclude certain rules from being applied.
  3. Ignore rules: You can specify rules that should be ignored for specific files or directories. This can be useful when certain rules are not applicable to your infrastructure code or when you intentionally want to exclude certain files from being checked.
  4. Plugin configuration: TFLint supports plugins that provide additional rules or functionality. Specific plugins can be enabled or disabled in this file, and their respective options set accordingly.

For an example of how to use this file, carry on reading!

How to install TFLint

If you use the popular package manager for Windows ‘chocolately’, you can easily install TFLint by running choco install tflint.

Using homebrew for Mac, simply run brew install tflint.

If you are using Linux or want to install from the source package, check out the TFLint page on GitHub to download it and get started:

  • Download tflint_linux_amd64.zip for Linux
  • Extract the downloaded ZIP file.
  • Add the extracted binary (tflint or tflint.exe) to a directory listed in your system’s PATH environment variable.

You can also use Docker to pull down the TFLint image using docker pull wata727/tflint.

After installation, you can verify that TFLint is properly installed by running tflint --version.

install tflint

Where are TFLint plugins installed?

By default, on Linux and macOS TFLint plugins are installed $HOME/.tflint.d/plugins.

On Windows, the default location is %USERPROFILE%\.tflint.d\plugins.

You can configure TFLint to use a custom plugin directory by setting the TFLINT_PLUGIN_DIR environment variable. If this variable is defined, TFLint will look for plugins in the specified directory instead of the default locations.

When you install a TFLint plugin, it typically consists of a single binary file or a set of related files that provide additional functionality or rules for TFLint to use during the linting process. The plugin’s files are placed in the appropriate plugin directory, and TFLint will automatically detect and load the plugins when it runs. TFLint installation. This allows for easier management and updates of the plugins without modifying the core TFLint installation.

To enable a plugin, edit the .tflint.hcl file and add the version and source.

For AWS and Azure plugins:

plugin "aws" {
  enabled = true
  version = "0.24.0"
  source  = "github.com/terraform-linters/tflint-ruleset-aws"
}

plugin "azurerm" {
  enabled = true
  version = "0.24.0"
  source  = "github.com/terraform-linters/tflint-ruleset-azurerm"
}

And then run tflint --init to have TFLint download and install the plugins.

tflint download

How to use TFLint - Example

  1. Install TFLint (see the section above on how to install if you have not done this already).
  2. Navigate to your project containing Terraform HCL configuration files.

I have the following configuration example file named main.tf

variable "region" {
  type = map(any)
  default = {
    "uk1" = {
      "region" = "uksouth",
    },
    "uk2" = {
      "region" = "ukwest",
    },
    "us" = {
      "region" = "eastus",
    }
    "us2" = {
      "region" = "eastus2",
    }
  }
}

resource "random_password" "password" {
  length           = 16
  special          = true
  override_special = "!#$%&*()-_=+[]{}<>:?"
}

variable "cidr" {
  default = "172.16.0.0/20"
}
  1. Run tflint and review the feedback.
    In my case, five issues are detected as Warnings:
tflint warnings
  1. I can then review each recommendation to fix my file according to the TFLint best practices.
  2. Repeat steps 3 & 4 until TFLint reports no further warnings or errors, indicating that your code meets the defined linting rules and best practices.

Ignoring TFLint Warnings

Let’s say I wanted to ignore the first recommendation, ‘Warning: terraform “required_version” attribute is required’.

By clicking on the link in the TFLint feedback, I can view the guidance on the rule, why it is enabled by default, and the recommendation on the action to take.

To disable this rule, I would need to exclude it using the .tflint.hcl file. Firstly create the file if this does not already exist and add the following:

rule "terraform_required_version" {
  enabled = false
}

Next time I run TFlint, I see the issue is now not reported, and I see four Warnings instead of my original five.

tflint warnings

How to configure TFLint

The .tflint.hcl file is the configuration file for TFLint, any configuration you wish to apply should be added here.

How to disable TFLint

TFLint can be removed from your workflow to stop code checks, or can be configured to ignore certain directories, files, rules, or modules rather than removing it completely.

Key points

TFLint is a valuable open-source Terraform tool that you can use to easily add Linting to your Terraform configuration files. Plugins for popular cloud providers can be installed to add further functionality and enable your team to increase the overall quality of your code!

Explore also how Spacelift makes it easy to work with Terraform. If you need any help managing your Terraform infrastructure, building more complex workflows based on Terraform, and managing AWS credentials per run, instead of using a static pair on your local machine, Spacelift is a fantastic tool for this. It supports Git workflows, policy as code, programmatic configuration, context sharing, drift detection, and many more great features right out of the box.

Note: New versions of Terraform will be placed under the BUSL license, but everything created before version 1.5.x stays open-source. OpenTofu is an open-source version of Terraform that will expand on Terraform’s existing concepts and offerings. It is a viable alternative to HashiCorp’s Terraform, being forked from Terraform version 1.5.6. OpenTofu retained all the features and functionalities that had made Terraform popular among developers while also introducing improvements and enhancements. OpenTofu is not going to have its own providers and modules, but it is going to use its own registry for them.

Manage Terraform Better with Spacelift

Build more complex workflows based on Terraform using policy as code, programmatic configuration, context sharing, drift detection, resource visualization and many more.

Start free trial