The more time that I spend writing Terraform and Terraform Modules, the more aware I have become of just how often I forget to run tools like terraform fmt and do the necessary code prettying things like making sure that my files all have ending new lines. As I was investigating how to better manage my Terraform READMEs to have the input and output variables generated (hint: terraform-docs) when I came across another project by Anton Babenko to implement pre-commit to Terraform.

Setting it up was really simple. On MacOS, I simply use Homebrew to install the necessary tools.

brew install pre-commit terraform-docs tflint

Once you have pre-commit installed, you can configure it to be used globally.

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

Finally, you can add the pre-commit-config file to your project. I like to include a couple of the generic pre-commit hooks in addition to the terraform specific ones.

cat << EOF > .pre-commit-config.yaml
repos:
    - repo: git://github.com/antonbabenko/pre-commit-terraform
      rev: $VERSION # Get the latest from: https://github.com/antonbabenko/pre-commit-terraform/releases
      hooks:
        - id: terraform_fmt
        - id: terraform_docs
    - repo: https://github.com/pre-commit/pre-commit-hooks
        rev: v2.4.0
        hooks:
          - id: check-merge-conflict
          - id: end-of-file-fixer
          - id: check-yaml
EOF

With that, every commit will validate that everything is proper before you can upload it. You can also run it against all file prior to commit with the pre-commit run -a command.