Use pre-commit to execute git hooks

Use pre-commit to execute git hooks

You may be very familiar with the following scenario: you've pushed a code change to your remote repository and now the code linting pipeline fails and you need to push another fix to make the linter proud. One way to prevent such behavior is to use a framework called "pre-commit".

With this framework, you can run scripts automatically before each git commit. This is especially useful if you work with linters like ansible-lint, for example, or want to rescan your code for unencrypted passwords before checking them in. This workflow can save you some pointless work and in this blog post, I'll show you how to utilize this using the ansible-linter pre-commit hook.

  1. Install pre-commit locally
pip install pre-commit

2. Check if the installation was successful

$ pre-commit --version
pre-commit 2.20.0

3. Add a pre-commit configuration

For this, you need a file called ".pre-commit-config.yaml" in your repository. You can use

pre-commit sample-config

for this but since we will use a prefabricated hook we can skip this step.

Tip: Check the official documentation for the full set of options for the top-level configuration.

4. Edit the .pre-commit-config.yaml and add ansible-lint as a hook

For this, we can copy and paste the example from the ansible-lint documentation. If you already use an existing Ansible Lint configuration in your repository, it will be automatically applied.

  - repo:
    rev: "v6.8.2"
      - id: ansible-lint

See the full list of predefined hooks here.

5. Install the git hook scripts

Switch back to your terminal and run:

$ pre-commit install
pre-commit installed at .git/hooks/pre-commit

6. (Optional) Run against all existing files

Once you have installed the git hook with pre-commit it will be executed as soon as new files are added. In order for it to look over all existing files, this step is necessary.

7. Do your git workflow

Now you can continue working in your repository as normal. As soon as you execute a git commit, the hook starts working. Depending on how you have configured the whole thing, you have to fix the error first or it will only give a warning and you can still push your changes to the remote repo.

If you have also included ansible-lint as a pre-commit hook, the result could look like this:

ansible-lint result with no fatals or warnings found


pre-commit documentation:

ansible-lint pre-commit setup:

Show Comments