- Allows developers to see and fix their code almost instantly.
- It keeps the codebase clean and standardized independently of the IDE being used.
- Besides linting, it also performs secret checks and many other things…
However, using it intensively could disrupt the developer’s workflow. It can shift their focus from bug fixing and adding new features to
linting.
In this blog post, I will walk you through, how we can add pre-commit hooks to our IaC
codebase.
Install pre-commit
Since pre-commit written in python you need to install the pre-commit module.
pip install pre-commit
Add a pre-commit Configuration
- create
.pre-commit-config.yamlfile. For demonstration purposes, I will add some basic hooks such ascheck-yaml,end-of-file-fixer,trailing-whitespaceandterraform_fmthook to format terraform files.
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v6.0.0
hooks:
- id: check-yaml
- id: end-of-file-fixer
- id: trailing-whitespace
- repo: https://github.com/antonbabenko/pre-commit-terraform
rev: v1.103.0
hooks:
- id: terraform_fmt
After add the configuration file, next step to instruct pre-commit to install the hooks.
pre-commit install
pre-commit installed at .git/hooks/pre-commit
Using pre-commit
In this example, variables.tf file generated and some variables are defined. Of course without any linting.
pre-commit run
check yaml...........................................(no files to check)Skipped
fix end of files.........................................................Passed
trim trailing whitespace.................................................Passed
Terraform fmt............................................................Failed
- hook id: terraform_fmt
- files were modified by this hook
variables.tf
As you see above, the terraform_fmt hook has failed because the file is not formatted well. At first run it failed but plugin has fixed the file.
index 6b70073..3f21cc1 100644
--- a/terraform/variables.tf
+++ b/terraform/variables.tf
@@ -1,5 +1,5 @@
variable "environment" {
- type = string
+ type = string
}
We can now add it to the staging area and run the pre-commit again.
pre-commit run
check yaml...........................................(no files to check)Skipped
fix end of files.........................................................Passed
trim trailing whitespace.................................................Passed
Terraform fmt............................................................Passed
At this time no issue detected. By the way, you can also run pre-commit for all files in the repository.
pre-commit run --all-files
Tip:
You can still bypass the hooks.
git commit -m "I will fix it next time" --no-verify
For more information you can check following urls about the pre-commit.
- https://git-scm.com/book/ms/v2/Customizing-Git-Git-Hooks
- https://pre-commit.com/
- https://github.com/antonbabenko/pre-commit-terraform