Use pre-commit to validate terraform files/projects

Git hook scripts can be used to launch scripts on every commit to format or validate files.

pre-commit is a framework to manage and maintain multi-language pre-commit hooks.

pre-commit-terraform is a collection of git hooks for terraform.

To start we need to install pre-commit:

brew install pre-commit
pip install pre-commit

When pre-commit is installed, you should be able to show what version you’re using:

$ pre-commit --version
pre-commit 3.6.0

Next, we will need to define our hooks using antonbabenko git hooks collection. Before using them, some tools need to be installed on our machine depending on your needs :

  • terraform-docs is required for terraform_docs hook.
  • terrascan is required for terrascan hook.
  • tfint is required for terraform_tflint hook.
  • tfsec is required for terraform_tfsec hook.
  • trivy is required for terraform_trivy hook.
  • infracost is required for infracost_breakdown hook.

All tools supported can be found on the README.md of the project.

For this example, I will only implement terraform fmt command, terraform-docs and tfint.

To add pre-commit configuration, we need to create a new file:

touch .pre-commit-config.yaml

Before continuing, we need to know the latest version of the collection. You can use curl and jq:

curl https://api.github.com/repos/antonbabenko/pre-commit-terraform/releases -s | jq '.[0].name' --raw-output

or just go to the release page.

Add this as content of .pre-commit-config.yaml:

repos:
- repo: https://github.com/antonbabenko/pre-commit-terraform
  rev: v1.86.0
  hooks:
    - id: terraform_fmt
    - id: terraform_docs
    - id: terraform_tflint

To test we can run all tests.

tests will only run on committed files.

$ pre-commit run --all-files 
Terraform fmt............................................................Passed
Terraform docs...........................................................Passed
Terraform validate with tflint...........................................Passed

After that every time files are committed on this repository, will trigger fmt, docs and tflint.

$ git commit -m 'chore: initial commit'
Terraform fmt............................................................Passed
Terraform docs...........................................................Passed
Terraform validate with tflint...........................................Passed
[main (root-commit) e698288] chore: initial commit
 31 files changed, 1013 insertions(+)
 create mode 100644 .gitignore
 create mode 100644 .pre-commit-config.yaml
 create mode 100644 infrastructure/rg.tf
 create mode 100644 infrastructure/sig.tf
 create mode 100644 infrastructure/st.tf

You can also define a git init template to include pre-commit by default:

DIR=~/.git-template
git config --global init.templateDir ${DIR}
pre-commit init-templatedir -t pre-commit ${DIR}

Thanks for reading my little notes. :)