Remove file from git history

Remove file from git history main picture
JAN24

Part of our contracts at App Dev Academy require code audits on different Ruby on Rails projects. And usually developers do same mistakes over and over again - they incude sensitive data, such as passwords, API keys for third party integrations, production database logins/passwords, other secrets into git repositories. This article will tell you how to remove sensitive data from git history completely.

Good example of such problem is including config/secrets.yml file into git repository. Ruby on Rails says that we should not include our secrets into git repository even in autogenerated comments for secrets.yml file:

# Do not keep production secrets in the repository,
# instead read values from the environment.

But if that already happened, there is a solution for this problem.

WARNING: before performing changes to git history, backup the whole repository first!

Also make sure that all pull requests are merged and nobody on your team has active branches.

To remove config/secrets.yml just execute this line in Terminal:

git filter-branch --tree-filter 'rm -f config/secrets.yml' HEAD

You can execute it multiple times for each file you want to remove by changing config/secrets.yml to your file path. After that your git history will be cleansed, sensitive files and all changes to them will be removed as they never existed.

All that's left is to push changes to remote repository (this command will replace content of remote repository with local one):

git push origin master -f

IMPORTANT: Don't forget to change passwords, API keys, regenerate certificates and never put them in repository again.

And finally you can implement that next really cool feature on your project:

git checkout -b new-cool-feature

Thanks for reading, keep your projects safe and we will see you in the next article! Keep on hacking :)