Pre-commit hooks for IaC
CI/CD · IaC
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
- bregman-arie/devops-resources — the Tools section
- pre-commit.com
- antonbabenko/pre-commit-terraform
How to apply it yourself
- Add
.pre-commit-config.yamlwith the three hooks. - Once —
detect-secrets scan > .secrets.baselineand commit the baseline. pre-commit installon every dev machine + a CI step.- Run it over the whole repo the first time and commit the formatting fixes as a separate commit.
- Once someone on the team tries to push a key and gets stopped — status Studied.