Prompt
How do I replace secrets that were committed to GitHub?
Latest observation
If a secret was committed to GitHub, treat it as compromised and do two things in parallel:
- Revoke/rotate the secret immediately
- Remove it from git history so it’s not still recoverable in the repo
1) Rotate or revoke the secret first
Even if you delete the file later, the secret may already have been copied, cached, or indexed.
Examples:
- API keys / tokens: regenerate a new one and invalidate the old one
- Database passwords: change the password
- SSH keys: generate a new key pair and remove the old public key from authorized systems
- Cloud credentials: disable the exposed access key and create a new one
2) Remove the secret from the repository history
Deleting the file in a new commit is not enough. You need to rewrite history.
Recommended tool: git filter-repo
This is the modern replacement for git filter-branch.
Install
pip install git-filter-repo
Example: remove a file from all history
git filter-repo --path path/to/secret-file --invert-paths
Example: replace a literal secret string everywhere
Create a replacement file, e.g. replacements.txt:
YOUR_OLD_SECRET==>REDACTED
Then run:
git filter-repo --replace-text replacements.txt
Alternative: BFG Repo-Cleaner
Useful for removing files or text quickly:
java -jar bfg.jar --delete-files secret-file.txt
or
java -jar bfg.jar --replace-text replacements.txt
3) Force-push the rewritten history
After rewriting history, push it back to GitHub:
git push --force --all
git push --force --tags
4) Tell collaborators to re-clone or reset
Because history changed, anyone else with the repo must update their local clone carefully. Often the safest path is:
- re-clone the repo
- or hard reset to the new history if they know what they’re doing
5) Check for other copies
Also remove the secret from:
- pull requests
- release artifacts
- CI logs
- issue comments
- forks
- GitHub Actions secrets/history if relevant
- caches or backups
6) Prevent it from happening again
- Use environment variables or a secret manager
- Add files to
.gitignore - Use pre-commit secret scanning tools:
- GitHub secret scanning
gitleakstrufflehog
- Keep example configs like
.env.examplewith dummy values only
Important note
If the secret was especially sensitive and publicly exposed, assume it may have been used already. Rotate it even if you’re also removing it from history.
If you want, I can give you:
- exact commands for your case,
- a step-by-step for GitHub,
- or instructions for removing a secret from a specific file or commit.