How to Remove Passwords from Git history

Sam A
3 min readOct 7, 2020

Have you had this problem that you have committed few passwords, secret or tokens in you code and now you want to clean up your code ?

I recently had the same issue and found a tool that can make this process very easy and i would like share it here for other people who are facing the same problem

  1. Navigate to the link below and download the zip

2. Unzip the file and rename it to just bfg and move it to the dicretory that you want to clone your repo and it fix it

Get a backup of your repo just in case, you can keep two mirror clones and work off one of them, also do a regular clone ( git clone your_repo_url ) just in case and keep it for backup. The safest way would be to push to a brand new repo.

Note: You need admin to be able to run these commands and change history, also make sure your master branch is not protected and you can push to master branch. In addition to that make sure you don’t have any outstanding Pull requests which may cause problems for you

3. git clone --mirror your_repo_url

4. Create a file called passwords.txt with you passwords/token/secrets that you want to be replaced with ***REMOVED***. This tool will replace all the occurrence of the strings that you have the passwrods.txt filewith “***REMOVED***” keyword.

superawesomeapikey1
password123

5. Run the BFG tool on the mirror folder that was created as per part 3

Note: make sure you have java install and its in your path. also we are running this command the same folder that we ran the git clone command and where bfg.jar was moved to.

java -jar bfg.jar --replace-text passwords.txt  your_repo

6. Change your directory to your git repo and run the following command to strip out all of the “dirty” data.

cd your_repo
git reflog expire --expire=now --all && git gc --prune=now --aggressive

7. Run Git Push command.

Note: Make sure you have admin access before doing this command and your master branch is not protected. Moreover also make sure you have some backups in place in case something went wrong and in case the repo got corrupted as result of this operation.

git push

References :

https://rtyley.github.io/bfg-repo-cleaner/

https://dev.to/edmondso006/removing-sensitive-data-from-git-history-5g63

--

--

Sam A

Senior DevOps Consultant, a tech enthusiast and cloud automation expert that helps companies improve efficiency by incorporating automation