Terraform Pre-Commit Hooks

By Josh Pollara on Apr 1, 2022
Terraform pre-commit hooks

There are many tools that can make sure your Terraform repo remains well-formated and tested. Using Git pre-commit hooks, one can easily incorporate these tools into everyday Terraform workflow.

1. Prerequisite: pre-commit

  • Install pre-commit
    • Pip: pip install pre-commit
    • Homebrew: brew install pre-commit
    • Apt: apt install pre-commit
    • Conda: conda install -c conda-forge pre-commit

2. Install third-party tools

  • tflint: A Pluggable Terraform Linter
  • tfsec: A static analysis security scanner
  • checkov: A static code analysis tool for infrastructure-as-code

3. Configuration

In the root of your Terraform repo, add a file called .pre-commit-config.yaml

default_stages: [commit]
- repo: https://github.com/antonbabenko/pre-commit-terraform
rev: v1.64.1
- id: terraform_fmt
- id: terraform_validate
- id: terraform_tflint
- id: terraform_tfsec
- id: checkov
- id: terraform_docs_replace
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.1.0
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files

4. Test

Manually run hooks:

pre-commit run -a

5. Install

To install the pre-commit hook, simply run:

pre-commit install

That’s it! You’re good to go locally.

5. Run in CI

Local pre-commits are super useful but they’re even better in CI. With Terrateam you get all of these tests out of the box. No configuration required.

Native Terraform checks and trusted third-party tools run directly from the Terrateam GitHub Action to make sure your code is formatted properly, validated, and secure.

We use cookies and similar technologies to provide certain features, enhance the user experience and deliver content that is relevant to your interests. Depending on their purpose, analysis and marketing cookies may be used in addition to technically necessary cookies. By clicking on "Agree and continue", you declare your consent to the use of the aforementioned cookies. Here you can make detailed settings or revoke your consent (in part if necessary) with effect for the future. For further information, please refer to our Privacy Policy .