In the previous post, we created a credential-less Terraform pipeline, however, this article is looking at improving this with Pre-Commit.
This is useful for preventing developers from committing code that is invalid or does not adhere to the team's coding standard. It can be used inside the pipeline and run locally so should provide consistency between the validation.
Here is an example of a .pre-commit-config.yaml file which can be used to provide a basic level of formatting and validation of the files.
- repo: https://github.com/antonbabenko/pre-commit-terraform
# Ensure coding standards are met e.g. snake_case or camelCase. Also comment format.
- id: terraform_tflint
# Ensure that the file formatting is correct.
- id: terraform_fmt
# Static analysis of potential security issues. TFSec also can be an option.
- id: checkov
# Provide automated documentation to the readme file.
- id: terraform_docs
- repo: https://github.com/pre-commit/pre-commit-hooks
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-json
Terraform Lint can help you find possible errors in your terraform code, inform you about deprecated syntax and enforce best practices such as snake_case vs camelCase.
Terraform format will improve the readability of your code by enforcing consistency and can reduce the noise in your commits.
This will allow you to generate documentation based on your Terraform code, this may include inputs, outputs, providers and resources.
Checkov will provide feedback on your Terraform with issues such as IAM policies not allowing credentials exposure, S3 buckets are not public and AWS Config being enabled in all regions.
This will help enforce compliance and will require you to add inline comments to skip the check on particular resources.
These will remove any spaces that are on the end of a line, as well as end the file with a blank line so you do not get the error message in the Version Control System.
These are quite handy when working in Cloud to just validate that these files are syntactically correct.