The .env file is typically located in the root directory of a project and is not committed to version control systems, such as Git. Instead, it is used to store sensitive information, such as database credentials, API keys, and passwords, which should not be publicly visible. By using an .env file, developers can keep their code and configuration separate, making it easier to maintain and deploy applications.
You can check the Youtube tutorial I created here
So if you’ve made a mistake like me and forgot to add “.env” to ‘.gitignore’ before pushing your code to your repository, you can follow these few simple steps to undo the catastrophe. 😅 We’re going to remove it not only from our git repository but most importantly from Git history as well.
Removing the file right away
The best thing to do now is to remove the file right away and add it to your .gitignore file.
# Secret
.env
Yep, the .gitignore file doesn't untrack already committed changes. So how can we fix this?
You can remove a file from Git by running the following command.
git rm -r --cached .env
If we then push this change, you will see that the file is gone in GitHub.
However, this didn’t completely solve our issue. If we look at our Git history, we can still find the file and expose the secrets!
To remove the file altogether, we can use the following command.
`git filter-branch --index-filter "git rm -rf --cached --ignore-unmatch .env" HEAD
You will get some warnings about this messing up your history as this goes through your whole history and 100% removes its existence. To push this, you have to run the following command.
git push --force
If we look at our history, we can still see the commits that include this .env file, but the content is empty.
Few, thanks for having our back Git!
Top comments (6)
It's a handy trick, but not foolproof: It won't erase any snapshots of the repo captured by internet archival services like archive.org, nor will it retrieve secrets that have already been snatched up by bots trawling for leaked credentials on GitHub.
Your best bet, if at all possible, is to invalidate any secrets that were included in the file and regenerate the credentials/keys.
Only from github's history, that's why I mention that you should generate new keys anyways because they're already exposed when that mistake happen.
Very informative article! Fortunately, Github has Secret Scanning in action. After receiving an email pointing out the mistake, this guide will be very handy to fix it!
A good article that will help a lot of folks roll back blunders from their repos.
Would also suggest using secret scanning tools like Talisman to avoid committing secrets
Thank you, github has secret scanning so you'll get informed instantly when you push your secrets in your repo then you can take action.
Wow i had no idea about the file still being exposed in git history. Very informative post ⭐️