Join experts to dive deep into IaC security and governance on August 27

➡️ Register for IaCConf

Terraform

What is TFLint and How to Lint Your Terraform Code

What is TFLint

🚀 Level Up Your Infrastructure Skills

You focus on building. We’ll keep you updated. Get curated infrastructure insights that help you make smarter decisions.

In this article, we will discuss ‘linting’, explaining what it is and why you should ‘lint’ before examining 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?

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.

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.

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.

TFLint automatically scans .tf files and reports potential issues. It works by analyzing Terraform code for stylistic errors, security problems, or provider-specific issues before deployment. 

You can extend functionality using plugins for cloud providers like AWS, Azure, or Google Cloud. Configuration is done via a .tflint.hcl file, where you can enable or disable rules and set custom checks.

How does TFLint differ from other validation tools

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. It doesn’t offer the same level of analysis and rule enforcement that dedicated linters provide.

Compared to terraform validate, TFLint offers deeper and more customizable analysis without requiring access to actual infrastructure.

.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. This file allows you to enable or disable specific plugins and set their respective options 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"
}

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

tflint download

How to use TFLint - Example

To use TFLint, first install it using the package manager or the binary. Then run it in your Terraform project directory.

For this example, let’s follow the steps below:

  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.

We 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 our case, five issues are detected as Warnings:
tflint warnings
  1. I can then review each recommendation to fix our file according to the TFLint best practices.
  2. Repeat steps 3 and 4 until TFLint reports no further warnings or errors, indicating that your code meets the defined linting rules and best practices.

Ignoring TFLint warnings

To ignore TFLint warnings, you can disable specific rules either inline within Terraform files or globally via the TFLint configuration file.

  • Use # tflint-ignore: <RULE_NAME> inline or above blocks to ignore rules. Replace RULE_NAME with the specific rule ID (e.g., aws_instance_invalid_type).
  • Add # tflint-ignore-file at the top of a .tf file to skip all rules for that file.
  • In .tflint.hcl, disable rules globally with  ignore_rules .

Let’s say, in our example, we wanted to ignore the first recommendation, Warning: terraform “required_version” attribute is required.

By clicking on the link in the TFLint feedback, we 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, we would need to exclude it using the .tflint.hcl file.

Firstly, create the file if it does not already exist and add the following:

rule "terraform_required_version" {
  enabled = false
}

The next time we run TFlint, we see that the issue has not been reported, and four Warnings instead of the original five.

tflint warnings

How to configure TFLint

To configure TFLint, create a .tflint.hcl configuration file in your project root and define rules, plugins, and settings specific to your Terraform codebase.

TFLint supports both built-in and plugin-based rules. Start by initializing with tflint --init to install any specified plugins. The configuration file allows you to enable or disable rules, set custom variables, and define provider-specific plugins. 

For example, to configure the AWS plugin:

plugin "aws" {
  enabled = true
  region  = "us-east-1"
}

You can also exclude specific rules globally or per directory. Use config { } blocks to customize settings like deep_check or module resolution behavior. After configuration, run tflint in the root directory to lint your Terraform code with your specified settings. This setup ensures consistent policy enforcement across your infrastructure code.

How to disable TFLint

To disable TFLint, you can either deactivate it globally, per project, or for specific rules depending on your use case.

  1. Disable globally: You can uninstall or disable the TFLint binary in your environment by removing it from your system PATH or uninstalling it entirely.
  2. Disable per project: Remove or rename the .tflint.hcl configuration file in the project root. Alternatively, avoid running tflint during your CI or local workflows.
  3. Disable specific rules or files
picnic-blog-banner

As it pursues its mission to transform grocery delivery logistics technology, Picnic Technologies wants to free its infrastructure team to do impactful work. Spacelift helps them to create the infrastructure they need, without the pain of manual Terraform processes. Now developers can work efficiently on more enjoyable work.

Spacelift customer case study

Read the full story

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 are 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 expands on Terraform’s existing concepts and offerings. It is a viable alternative to HashiCorp’s Terraform, being forked from Terraform version 1.5.6.

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