How to keep your DevOps code tidy with pre-commit

How to keep your DevOps code tidy with pre-commit

Problem:

Ensure that your configuration code is formatted and validated to the best practice standards. Make this process automatic and catch errors early before committing them in your repository.

Use pre-commit tool with collection of hooks from Gruntwork:

pre-commit - is an open-source tool that eases the process of maintaining multi-language pre-commit hooks in your project.

You just specify a list of hooks that you need for your project in a .pre-commit-config.yaml file and pre-commit will manage the installation and execution of hooks in any language before every commit.

Prerequisite:

Need pip installed on the Linux machine:

sudo apt update;
sudo apt install python3-pip;
pip3 --version

Install pre-commit tool:

To install pre-commit use:

pip install pre-commit;
pre-commit --version

Configure pre-commit in your project:

  1. Create a file named .pre-commit-config.yaml
  2. Open the file and add the following entries:
    repos:
    - repo: https://github.com/gruntwork-io/pre-commit
     rev: v0.1.17
       - id: terraform-fmt
       - id: terraform-validate
       - id: tflint
       - id: shellcheck
       - id: gofmt
       - id: golint
    
  3. Get the latest from: https://github.com/gruntwork-io/pre-commit/releases hooks:
  4. To add several repositories just specify another repo item in the list. For example:
    repos:
    - repo: https://github.com/gruntwork-io/pre-commit
     rev: v0.1.17
     hooks:
       - id: terraform-fmt
       - id: terraform-validate
       - id: tflint
       - id: gofmt
       - id: golint
    - repo: https://github.com/pre-commit/pre-commit-hooks
     rev: v4.1.0  # Use the ref you want to point at
     hooks:
       - id: trailing-whitespace
    
  5. Install pre-commit: pre-commit install
  6. Commit your message and check the output:
    output
  7. To get the list of other pre-commit hooks look here:
    https://pre-commit.com/hooks.html
    Some of the interesting supported hooks are:

Advantages of the tool:

  1. For teams, this tool is best used in CI pipelines during merge events. This ensures that code is tidied by developers.
  2. Ensures that your code is checked according to the industry best practices
  3. Easily set up, all you need to keep and transfer .pre-commit-config.yaml file across different projects inside your team
  4. Create your own hooks

Disadvantages of the tool:

  1. Slows your team's workflow pace. Make them commit less.
  2. Some of the pre-commit tools automatically format and change the code without your allowance. If the hook provider will be hacked, you can end up with malicious code running in your project. But this can be avoided by making your own local hooks.

Reference:

  1. A collection of pre-commit hooks used by Gruntwork tools
  2. Supported hooks
  3. pre-commit-hooks
  4. Git Hooks