Skip to content

Pre-commit hooks for IaC

CI/CD · IaC
Studied

Problem

A Terraform/Ansible/YAML repository keeps receiving PRs with unformatted code, version drift, secrets in .tf files (aws_access_key = "AKIA...") and YAML with broken nesting. Linters exist, but nobody wants to run them by hand, and CI catches problems only after the push.

Solution

pre-commit is "a framework for managing and maintaining multi-language pre-commit hooks". Put three proven hooks under it: tflint (Terraform), yamllint (YAML) and detect-secrets (secrets). One config, pinned versions, the same checks locally and in CI.

Example

.pre-commit-config.yaml:

repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v5.0.0
    hooks:
      - id: end-of-file-fixer
      - id: trailing-whitespace
      - id: check-yaml

  - repo: https://github.com/antonbabenko/pre-commit-terraform
    rev: v1.96.2
    hooks:
      - id: terraform_fmt
      - id: terraform_tflint
        args: [--args=--config=.tflint.hcl]

  - repo: https://github.com/adrienverge/yamllint
    rev: v1.35.1
    hooks:
      - id: yamllint
        args: [-c=.yamllint]

  - repo: https://github.com/Yelp/detect-secrets
    rev: v1.5.0
    hooks:
      - id: detect-secrets
        args: ['--baseline', '.secrets.baseline']

Setup:

pip install pre-commit
pre-commit install
detect-secrets scan > .secrets.baseline
pre-commit run --all-files   # backfill over existing code

In CI — a single step:

- uses: pre-commit/action@v3.0.1

When to use

  • Any repository with IaC, Ansible or Kubernetes manifests.
  • When the team has 3+ people — formatting drift becomes more expensive than setting up hooks.

Source

How to apply it yourself

  1. Add .pre-commit-config.yaml with the three hooks.
  2. Once — detect-secrets scan > .secrets.baseline and commit the baseline.
  3. pre-commit install on every dev machine + a CI step.
  4. Run it over the whole repo the first time and commit the formatting fixes as a separate commit.
  5. Once someone on the team tries to push a key and gets stopped — status Studied.