How do you prevent secrets from leaking through your CI/CD pipeline?
Short answer
Use defense in depth: pre-commit hooks (e.g. gitleaks) catch secrets before they ever land, server-side CI scanning catches what slips past, and periodic full-history scans find old leaks. Critically, a secret that reached a remote repo must be treated as compromised and rotated — deleting the commit doesn't help because it lives in history, forks, and logs. Pair this with a real secrets manager so secrets aren't in code at all.
Hard-coded credentials are one of the most common and damaging mistakes in software, and the pipeline is where you catch them. A good answer is layered.
Catch it before it lands: pre-commit
A pre-commit hook (using a scanner like gitleaks or detect-secrets) runs on the developer's machine and blocks the commit if it spots an API key, private key, or token. This is the cheapest place to stop a leak — the secret never even reaches the server. The weakness: hooks are local and can be bypassed or skipped, so they can't be your only line.
Catch what slips past: server-side CI
Because hooks aren't enforceable, run the same scanning server-side in CI on every push and pull request, and ideally as a platform-level scan (GitHub/GitLab native secret scanning) that the developer can't disable. This is the enforceable gate.
Find old leaks: history scanning
Secrets committed months ago still sit in git history. Periodically scan the full history, and use push protection so platform-detected secrets are blocked at push time.
The non-negotiable: rotate
Here's the part juniors miss. Once a secret has reached a remote repository, it is compromised — full stop. It persists in history, in clones, in forks, and in CI logs. Deleting the commit or rewriting history does not make it safe. The only correct response is to rotate the credential immediately.
Better: don't have secrets in code
The root fix is a secrets manager (Vault, cloud KMS/secret stores) so applications fetch secrets at runtime and CI injects them as masked variables — there's nothing to leak.
What interviewers look for
They want the layered model, the insistence on rotation over deletion, and the recognition that secrets managers remove the problem at its source.
Likely follow-ups
- Why isn't deleting the offending commit enough?
- Where should secrets actually live instead of in code?
- Why run scanning both pre-commit and server-side rather than just one?