DEV Community

Lewis Stevens for AWS Community Builders

Posted on

Improve a credential-less Terraform pipeline with Pre-Commit

In the previous post, we created a credential-less Terraform pipeline, however, this article is looking at improving this with Pre-Commit.


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.

repos:
  - repo: https://github.com/antonbabenko/pre-commit-terraform
    rev: v1.64.1
    hooks:
      # 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
    rev: v4.0.1
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-yaml
      - id: check-json
Enter fullscreen mode Exit fullscreen mode

Terraform Lint

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

Terraform format will improve the readability of your code by enforcing consistency and can reduce the noise in your commits.

Terraform Docs

This will allow you to generate documentation based on your Terraform code, this may include inputs, outputs, providers and resources.

Checkov

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.

Trailing Whitespace / End Of File Fixer

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.

Check Yaml / Json

These are quite handy when working in Cloud to just validate that these files are syntactically correct.

Additional Pre-Commit Hooks

For additional Pre-Commit hooks, please see Pre-Commit's Github and Anton Babenko's Github repositories.

Top comments (1)

Collapse
 
stormytalent profile image
StormyTalent

Perfect!