Keep secrets out of Git
In this task you'll stop secrets reaching your repository.
Once a secret is pushed it should be treated as leaked: forks, clones and caches keep it even if you delete the commit. Prevention is cheap: a .gitignore for local files, push protection to block known secret formats, and secrets kept in Key Vault or the pipeline's secret store.
If one does get in: rotate it first, then clean the history.
Example. Ironbridge Payments turned on push protection after a storage key reached GitHub. A week later it blocked a push containing a connection string, and the developer moved it to Key Vault instead.
Before you start
You need: A GitHub repository. Time: 15 minutes.
Where to look
- GitHub
- Repository
- Settings
- Advanced Security
- Secret Protection
Steps
- Add a .gitignore with at least
.env,*.tfstate,*.tfstate.*and.terraform/.Terraform state can hold secrets in plain text. - Open Settings, then Advanced Security (or Code security), and turn on Secret Protection and Push protection.Free for public repositories.
- Test it: add a fake key in the format of a cloud token to a file and try to push. GitHub refuses and says why.
- Remove the line and commit again. Never use real secrets to test.
Commands
# A starter .gitignore for DevOps repositories
cat >> .gitignore <<'EOF'
.env
*.tfstate
*.tfstate.*
.terraform/
*.pfx
EOF
git add .gitignore && git commit -m "Ignore secrets and state"
Watch out for
- Cost
- Free for public repositories; paid for private ones on organisation plans.
- Security
- Deleting the file in a new commit doesn't remove it from history. Rotate the secret.
- Common mistakes
- Committing .tfstate or .env files, and testing scanners with real keys.
Clean up
Nothing to clean up.
Words to know
- .gitignore
- A file listing paths Git should never add, such as .env and *.tfstate.
- Push protection
- GitHub secret scanning that blocks a push containing a recognised secret.
- Rotate
- Replace a secret with a new one, so the old one stops working.
Tick off each step and track your progress in the guide.
Open this task in DevOps, Hands On