Git从Repo中删除敏感数据
posts/git%E4%BB%8Erepo%E4%B8%AD%E5%88%A0%E9%99%A4%E6%95%8F%E6%84%9F%E6%95%B0%E6%8D%AE如果将敏感数据(例如密码或 SSH 密钥)提交到 Git 仓库,是可以将其从历史记录中删除的。
如果要从仓库的历史记录中彻底删除不需要的文件,可以使用git filter-branch
命令。
如果其历史记录中没有包含敏感数据仓库的本地副本,则克隆仓库到本地计算机。
$ git clone https://github.com/YOUR-USERNAME/YOUR-REPOSITORY
> Initialized empty Git repository in /Users/YOUR-FILE-PATH/YOUR-REPOSITORY/.git/
> remote: Counting objects: 1301, done.
> remote: Compressing objects: 100% (769/769), done.
> remote: Total 1301 (delta 724), reused 910 (delta 522)
> Receiving objects: 100% (1301/1301), 164.39 KiB, done.
> Resolving deltas: 100% (724/724), done.
切换仓库的工作目录
$ cd YOUR-REPOSITORY
运行以下命令,将PATH-TO-YOUR-FILE-WITH-SENSITIVE-DATA
替换为要删除的文件的路径,而不仅仅是其文件名。这些参数将:
- 强制 Git 处理但不检出每个分支和标记的完整历史记录
- 删除指定的文件,以及因此生成的任何空提交
- 覆盖现有的标记
$ git filter-branch --force --index-filter \
"git rm -r --cached --ignore-unmatch PATH-TO-YOUR-FILE-WITH-SENSITIVE-DATA" \
--prune-empty --tag-name-filter cat -- --all
> Rewrite 48dc599c80e20527ed902928085e7861e6b3cbe6 (266/266)
> Ref 'refs/heads/main' was rewritten
将含有敏感数据的文件添加到 .gitignore
以确保不会再次意外提交它。
$ echo "YOUR-FILE-WITH-SENSITIVE-DATA" >> .gitignore
$ git add .gitignore
$ git commit -m "Add YOUR-FILE-WITH-SENSITIVE-DATA to .gitignore"
> [main 051452f] Add YOUR-FILE-WITH-SENSITIVE-DATA to .gitignore
> 1 files changed, 1 insertions(+), 0 deletions(-)
仔细检查是否已从仓库历史记录中删除所需的所有内容,并且所有分支均已检出。
对仓库的状态感到满意后,强制推送本地更改以覆盖 GitHub 仓库,以及已向上推送的所有分支:
$ git push origin --force --all
> Counting objects: 1074, done.
> Delta compression using 2 threads.
> Compressing objects: 100% (677/677), done.
> Writing objects: 100% (1058/1058), 148.85 KiB, done.
> Total 1058 (delta 590), reused 602 (delta 378)
> To https://github.com/YOUR-USERNAME/YOUR-REPOSITORY.git
> + 48dc599...051452f main -> main (forced update)
要从标记的发行版删除敏感文件,还需要强制推送 Git 标记:
$ git push origin --force --tags
> Counting objects: 321, done.
> Delta compression using up to 8 threads.
> Compressing objects: 100% (166/166), done.
> Writing objects: 100% (321/321), 331.74 KiB | 0 bytes/s, done.
> Total 321 (delta 124), reused 269 (delta 108)
> To https://github.com/YOUR-USERNAME/YOUR-REPOSITORY.git
> + 48dc599...051452f main -> main (forced update)