How to Set Up gitleaks + pre-commit + CI [2026]

A terminal-first, defense-in-depth secrets workflow for 2026: staged-only hooks, CI full-history scans, baselines for legacy repos, and sane allowlists.

Part of theDev Tools & AI Workflow series
Computer screen displaying code and terminal prompts

I’ve watched teams spend a week arguing about “security standards” and then ship a .env with a real Stripe key because the commit hook was slow and the CI output was unreadable.

So yes, this post is about a gitleaks pre-commit ci setup. But the real point is: secret scanning is a UX problem disguised as a security problem. If it’s fast and obvious, developers comply. If it’s slow and noisy, they’ll bypass it. Every time.

By the end of this, you’ll have a working setup that:

  • blocks obvious secrets before they ever get committed (fast, staged-only)
  • enforces the policy in CI (full scans, consistent rules)
  • actually works on day 1 for legacy repos (baseline strategy instead of “stop the world”)
  • surfaces findings as PR annotations (SARIF) so nobody goes log-diving

If you already have Git hooks and CI, this is a ~30–45 minute setup. The rest of the time is the only part that matters. Rule tuning, path exclusions, and exception hygiene so the scanner stays credible.

What is Gitleaks?

Gitleaks is an open-source secret scanning tool that detects credentials and sensitive values in source code and Git history using configurable detection rules.

A large screen displays "chatgpt atlas" logo

It’s not the only scanner worth using. But for most teams it hits the sweet spot: easy to run locally, easy to run in CI, and configurable enough that you can beat down false positives instead of telling everyone to “just deal with it.”

I treat it as one layer in defense-in-depth. Your platform should still do secret protection too. GitHub’s secret scanning and push protection exist for a reason, and they keep getting better (GitHub).

→ Related: AI Code Review in Your CI/CD Pipeline: 2026 Setup

Quick setup: pre-commit (staged-only) + CI (full scan)

This is the minimum viable pipeline I recommend in 2026. Five steps.

a black and white photo of three different products
  1. Install gitleaks on dev machines (Homebrew, asdf, devcontainer, etc.). Pin a version.
  2. Add pre-commit and a hook that scans only staged files.
  3. Add a gitleaks.toml (or start with the default config and extend it).
  4. Add a CI job that scans the repo (and optionally the full Git history), and outputs SARIF.
  5. Add a baseline/allowlist strategy so existing repos can ship without breaking every PR.

If you do just steps 1–4, a legacy repo will probably fail instantly. That’s where most tutorials stop. Don’t.

Run gitleaks in pre-commit (fast staged-only scanning)

I like pre-commit because it standardizes hook installation across macOS/Linux/Windows and works well in polyglot repos. It’s a hook framework, not a security tool (pre-commit).

Chatgpt atlas logo displayed on a large screen

Install pre-commit

Add it to your dev dependencies. I usually do:

  • Python repos: pip install pre-commit (or lock it via requirements-dev.txt)
  • Non-Python repos: still fine to use pipx or uv tool install so you don’t pollute global Python

Then:

  • pre-commit install

Add `.pre-commit-config.yaml`

Create a .pre-commit-config.yaml at the repo root. A pragmatic config looks like this:

yaml
repos:
  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.18.4
    hooks:
      - id: gitleaks
        name: gitleaks (staged)
        args: ["protect", "--staged", "--verbose", "--redact"]

A few opinions I’m not shy about:

  • protect --staged is the whole point. Staged-only keeps the hook fast. On normal feature work, this should feel like a formatter. Not an audit.
  • --redact prevents accidental “leak the leak” in output. People paste CI logs into Slack. Don’t print raw secrets.
  • Pin rev. Floating “latest” is how you wake up to surprise breakages on a Tuesday.

Concrete performance expectation: staged-only scans should usually feel sub-second to a couple seconds, depending on what you staged. If it takes 10+ seconds routinely, devs will start bypassing. Not because they’re evil. Because they’re trying to ship.

Make it terminal-first

The fastest way to kill this rollout is forcing people into a web UI to figure out what happened.

Let the hook print:

  • which file
  • which rule ID
  • a short hint that points to the fix

Then let CI be the auditor.

If you also care about secrets reaching AI coding tools, pair this with a redaction workflow. I wrote a separate playbook on AI security for that exact “oops I pasted prod keys into a CLI” moment.

Run gitleaks in CI (GitHub Actions + SARIF annotations)

Local hooks are for speed. CI is for enforcement.

If you only do local hooks, someone will commit with --no-verify or push from a different environment. That’s fine. Humans are humans.

CI makes it non-negotiable.

GitHub Actions workflow (with SARIF upload)

You want two outputs:

  1. a failing check when a new leak is introduced
  2. SARIF so results show up as annotations in the PR, not buried in logs

GitHub supports SARIF for code scanning (GitHub).

Here’s a workflow I’ve used as a starting point:

yaml
name: secret-scan
on:
  pull_request:
  push:
    branches: [main]

jobs:
  gitleaks:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      security-events: write
      pull-requests: read

    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Run gitleaks
        uses: gitleaks/gitleaks-action@v2
        with:
          args: >-
            detect
            --source .
            --report-format sarif
            --report-path gitleaks.sarif
            --redact

      - name: Upload SARIF
        uses: github/codeql-action/upload-sarif@v3
        with:
          sarif_file: gitleaks.sarif

Notes that matter:

  • fetch-depth: 0 enables full-history scanning when you want it. It also makes checkout heavier. That’s the trade.
  • security-events: write is required for SARIF upload.
  • Use the official action (gitleaks-action) instead of curling random binaries. Fewer moving parts.

Full-history vs PR diff: pick intentionally

There are two modes teams muddle together:

  • PR mode: scan what changed. Fast. Great feedback loop.
  • History mode: scan the repo with a full fetch and options that walk commits. Slower. Great for auditing and eliminating the “it was already there anyway” excuse.

I often do both:

  • PRs: scan the working tree (or changed files) and annotate
  • nightly or main branch: deeper scan (history), alert security/appsec

A very normal number in medium repos: a full-history scan can go from <10 seconds (tiny repo) to minutes (big monorepo + long history). Don’t pretend it’s free.

Handle existing repos: baseline-first rollout (audit → baseline → ratchet)

This is where secret scanning projects go to die.

A legacy repo usually has:

  • old test credentials checked in “temporarily” in 2019
  • vendor keys in docs
  • private keys inside fixtures/
  • and a handful of false positives that will annoy everyone

If you flip CI enforcement on immediately, you’ll block every PR and create instant backlash. You’ll also train the org to treat security tooling as an obstacle instead of a guardrail.

The rollout I recommend

  1. Week 1: audit-only
    • run gitleaks in CI but don’t fail the build
    • produce SARIF and let people see what it flags
  2. Week 2: baseline the current state
    • capture existing findings as “known debt”
    • document owners and remediation timelines
  3. Week 3+: ratchet down
    • fail CI only on new findings
    • tighten rules as you burn down the backlog

This is exactly how teams adopt quality tooling without riots. Same playbook as linting, type checking, or formatter enforcement.

Baseline options (two practical choices)

You basically have two baseline approaches:

Option A: ignore file (`.gitleaksignore`)

  • Create an ignore list of known fingerprints.
  • Commit it.
  • CI fails only on new fingerprints.

This is the simplest approach for most teams.

Option B: baseline artifact in CI

  • Store the baseline output somewhere (artifact, S3, etc.).
  • Compare on each run.

Option B is heavier. I rarely see teams maintain it well.

Concrete policy I like: allow 30 days to remediate baseline findings, with a weekly burn-down. Past that, you’re just teaching the team that “security debt” is permanent.

If you’re rolling this out org-wide, bake it into scaffolding. At Rise People, I learned that “compliance baked into scaffolding beats compliance review at PR time” because it removes judgment calls from the moment people are trying to ship.

Ignore false positives safely (allowlists, path excludes, rule tuning)

False positives are the number one cause of security tooling fatigue. But “just ignore it” is how you end up with a scanner that’s technically present and functionally useless.

Treat exceptions as policy-as-code.

Prefer scoped allowlists over broad rule disables

The safest order of operations:

  1. exclude known generated/vendor paths
  2. allowlist specific test fixtures
  3. add stopwords for obvious non-secrets
  4. tune a single rule (regex) only when you can explain it

Concrete examples that are sane:

  • ignore dist/, vendor/, node_modules/, coverage/
  • ignore **/*.snap if your snapshots contain fake tokens
  • allowlist docs/examples/ if you use sk_live_... style strings as placeholders

If your allowlist is “ignore all files under src/” you’ve just built a placebo.

Socialize exceptions to avoid weakening security

Two tactics that actually work:

  • Require an owner on every allowlist entry (a team or a person)
  • Expire allowlist entries (a date, or a ticket link)

If you don’t do this, .gitleaksignore turns into a junk drawer. I’ve watched it happen.

If you want a broader security posture, tie this into your AI security and LLM security efforts too. In 2026, secrets don’t just leak to Git. They leak into logs, traces, and LLM prompts.

PR UX: get out of logs and into annotations (SARIF + comment summary)

Developers act on what’s directly in front of them.

A failing CI job with 800 lines of log output is basically security theatre. People will re-run, scroll, and then ask in Slack.

SARIF is the fix. It turns secret findings into inline annotations.

Add a PR comment summary (optional)

I like a short PR comment that says:

  • count of findings
  • which files
  • link to the Code Scanning tab

Keep it high-signal. No walls of text.

If you’re already doing structured PR workflows, this pairs well with stacked PRs because small diffs plus good annotations reduce time-to-fix.

Here’s the simplest rule: if the developer needs to click more than once to understand what to do, you will get bypasses.

CI + hooks comparison table (what runs where)

This is the mental model I want teams to share.

LayerTriggerScopeTypical timeOutputPurpose
pre-commit hook`git commit`staged files only0.5–3sterminalstop mistakes early
PR CI (GitHub Actions)`pull_request`working tree / PR changes10–60sSARIF annotationsmake it actionable
main/nightly CI`push` / schedulefull repo + optional history30s–5m+SARIF + alertscatch bypasses + audit

Numbers are real-world expectations, not guarantees. If your PR scan is 5 minutes, you’ve already lost.

gitleaks vs TruffleHog vs platform secret scanning

People ask this because they want to pick one tool and be done.

Bad news: you probably want two.

Gitleaks

  • Great for deterministic rules and team-controlled configuration.
  • Fits the “terminal-first + CI enforcement” workflow.

TruffleHog

TruffleHog focuses heavily on finding and verifying credentials where possible, and it’s widely used for broader scanning contexts too (Truffle Security).

If your biggest pain is “tons of entropy false positives,” TruffleHog’s approach can be attractive.

GitHub Secret Scanning / Push Protection

GitHub’s secret scanning and push protection are a separate layer and should stay enabled when you can (GitHub).

My stance:

  • Use gitleaks to enforce your org’s rules in the repo.
  • Use platform secret protection to catch what humans and tooling miss.

Defense in depth beats tool holy wars.

Remediation playbook: what to do after a leak is detected

Secret scanning without remediation is just shame-as-a-service.

When gitleaks (or anything) flags a real secret:

  1. Rotate the credential immediately. Minutes matter, not days.
  2. Invalidate tokens/sessions if the secret could be used to mint access.
  3. Remove it from the repo (and consider history rewrite if it’s truly sensitive).
  4. Add a test or a rule to prevent the same class of leak again.
  5. Do a quick blast-radius review: what could that secret access? What logs/traces might contain it?

Concrete rule: if rotation takes more than 24 hours, treat it as an incident. That’s how you keep the process honest.

If your team is already building agentic tooling, assume secrets will show up in prompts unless you actively prevent it. I’ve been building and maintaining 25+ browser-based developer tools on this site (/tools). One lesson that keeps showing up: safety features only work when they’re the default. Optional safety is just future regret.

Policies that reduce developer backlash (while improving security)

If you want this to stick, you need a social contract, not just a YAML file.

Here’s what I’ve seen work:

  • Phased rollout: audit → baseline → ratchet.
  • Break-glass: allow --no-verify locally, but CI is the final gate. If someone truly must merge, require a security-approved override.
  • Performance budget: commit hook must stay under 3 seconds most of the time. Treat regressions as tooling bugs.
  • Clear exception process: PR that modifies allowlists must be reviewed by a designated owner.
  • Metrics: track “new findings per week” and “time to rotation.” If you can’t measure it, you can’t improve it.

This is one of those things where the boring answer is actually the right one. If you treat secrets hygiene like linting, you’ll get adoption. If you treat it like a moral failing, you’ll get bypasses.

Here’s the official GitHub overview video if you want to align this with platform secret protection:

One prediction: by 2027, teams will treat secret scanning as a first-class developer experience feature. Not “security tooling.” The teams that win will be the ones whose scanners feel like a fast, helpful teammate, not a gatekeeping cop.

Photo by Bernd 📷 Dittrich on Unsplash.

Continue reading

Computer screen displaying code and terminal prompts

AI Code Review in Your CI/CD Pipeline: 2026 Setup

Every vendor shipped a 2026 'best tools' listicle. None shipped the YAML. Here's a complete, copy-pasteable GitHub Actions config that wires AI code review into your pipeline — triggers, secrets, cost caps, and a real merge gate.

GitHub Actions vs CircleCI 2026: Which CI/CD Pipeline Wins?

GitHub Actions vs CircleCI 2026: Which CI/CD Pipeline Wins?

I'd pick GitHub Actions for solo devs and GitHub-native teams who want zero-friction setup; I'd pick CircleCI for performance-obsessed teams who need faster parallelism and fine-grained resource control. The split isn't about features — it's about where your bottleneck actually lives.

Open laptop with code on screen, neon lighting

How to Reduce Rust Compile Time [2026] (sccache + mold)

A measurable 2026 playbook to reduce Rust compile time: profile with Cargo timings, fix the build graph, get real sccache hit rates, and cut link time with mold.

Frequently Asked Questions

How do I run gitleaks in pre-commit?

Add a gitleaks hook to your `.pre-commit-config.yaml` and run `pre-commit install`. Use `gitleaks protect --staged` so it scans only staged files, which keeps commit-time checks fast.

How can I ignore false positives in gitleaks?

Use a scoped allowlist approach: exclude known safe paths (like generated folders) and add specific ignore entries for known test fixtures. Avoid disabling entire rules unless you can explain the risk and have an owner for the exception.

What’s the difference between gitleaks and trufflehog for secret scanning?

Gitleaks is great for rule-based detection you can version and enforce consistently in hooks and CI. TruffleHog emphasizes finding and, where possible, verifying credentials, which can reduce entropy-style false positives. Many teams use both alongside platform secret scanning for defense in depth.

Cite this article
Kunal Ganglani (2026, August 19). How to Set Up gitleaks + pre-commit + CI [2026]. Kunal Ganglani. Retrieved August 19, 2026, from https://www.kunalganglani.com/blog/gitleaks-pre-commit-ci-setup

Comments