Skip to main content

Security and hardening · Beginner · 12 min

How to Keep Passwords and API Keys Out of Git

By Padding · Updated 15 Nov 2026
Ubuntu 26.04 · Git 2.53

You will keep secrets in a git-ignored .env file, commit a safe template instead, stop a commit that contains a key with a pre-commit hook, and learn what to do when a secret has already been committed.

On this page

A password in a Git repository is a password you cannot take back. Git keeps every version of every file, so deleting the line in a later commit leaves the secret in the history. Bots scan public repositories for keys within minutes of a push, and a private repository is one leaked clone or one new teammate away from being read by the wrong person.

The fix is a habit, not a tool: secrets live outside the repository and reach your program through its environment. In this tutorial you will set that up, add a safety net that refuses commits containing key-shaped text, and learn the correct response when a secret has already been committed. The fake keys in the examples are not real.

Step 1 · Create a project with a secrets file

Make a new folder and start a repository. The .env file holds the settings that differ per machine, including secrets. Names in capitals, one NAME=value per line, is the format almost every framework reads.

Bash
mkdir secrets-demo
cd secrets-demo
git init
cat > .env <<'EOF'
DATABASE_URL=postgres://appuser:fake-password-1234@localhost:5432/appdb
STRIPE_SECRET_KEY=sk_test_FAKEfakeFAKEfake1234567890
EOF

git init prints Initialized empty Git repository. The two values are made up, but treat them as if they were live. Right now, git status would offer the file for committing:

Bash
git status --short

The output is ?? .env. The two question marks mean Git sees a new file it does not track yet. If you ran git add . now, the secrets would go in.

Step 2 · Tell Git to ignore the file

Create a .gitignore file and list .env in it. Do this before the first commit, and before you ever create the secrets file in a real project.

Bash
printf '.env\n.env.*\n!.env.example\n' > .gitignore
git status --short

The patterns mean: ignore .env, ignore .env.production and any other .env.* file, but do not ignore .env.example, which you will create next. The status now shows only ?? .gitignore, and .env is gone from the list. When a file is ignored and you wonder which rule did it, ask Git:

Bash
git check-ignore -v .env

The output names the rule and the line, .gitignore:1:.env followed by the file name.

Step 3 · Commit a template instead

A teammate, or you on a new laptop, needs to know which settings the project expects. Commit a copy of the file with the secret values replaced by dummy values:

Bash
cat > .env.example <<'EOF'
DATABASE_URL=postgres://USER:PASSWORD@localhost:5432/DBNAME
STRIPE_SECRET_KEY=
EOF
git add .gitignore .env.example
git commit -m "Add env template and ignore real secrets"

Name the files you add one by one, as above, instead of using git add .. It is slower and it keeps a stray secrets file out of the commit.

Check it worked

Bash
git ls-files

The output lists .env.example and .gitignore, and not .env. A new machine copies the template with cp .env.example .env and fills in real values.

Step 4 · Read the secrets from the environment

Your program should read DATABASE_URL and the others from its environment, not from a string in the code. Every language has a one-line way to do it: process.env.DATABASE_URL in Node.js, os.environ["DATABASE_URL"] in Python. Many frameworks load .env for you in development. Without a framework, your shell can load the file:

Bash
set -a
. ./.env
set +a
echo "Database host part: ${DATABASE_URL##*@}"

set -a marks every variable defined next as exported, so child programs see it. The . command reads the file, and set +a turns the marking off again. The echo prints only the part of the URL after the @, here localhost:5432/appdb, so the check does not print the password. Never print a whole secret into your terminal while screen-sharing or into a log. This simple loader works for plain NAME=value lines. A value with spaces or a $ in it needs quotes, and a framework's own loader handles those cases better.

On a production server, set the variables in the service's configuration, such as an EnvironmentFile= line in a systemd unit with mode 600, or your host's secrets setting. Do not copy a .env file between machines in chat.

Step 5 · Add a safety net with a pre-commit hook

People make mistakes, so add a check that runs before every commit. A Git hook is a script in .git/hooks/. If the pre-commit script exits with a non-zero code, Git cancels the commit. This one searches the lines you are about to commit for text shaped like keys:

Bash
cat > .git/hooks/pre-commit <<'HOOK'
#!/bin/sh
# Refuse to commit lines that look like secrets.
pattern='AKIA[0-9A-Z]{16}|-----BEGIN [A-Z ]*PRIVATE KEY-----|sk_(live|test)_[0-9A-Za-z]{16,}|(api[_-]?key|secret|passwd|password|token)[A-Za-z0-9_]*[[:space:]]*[:=][[:space:]]*["'"'"']?[A-Za-z0-9/+_.-]{16,}'

if git diff --cached -U0 | grep -E '^\+' | grep -v '^+++' | grep -E -i -q "$pattern"; then
  echo "pre-commit: this commit adds text that looks like a secret." >&2
  echo "Remove it, or bypass once with: git commit --no-verify" >&2
  exit 1
fi
HOOK
chmod +x .git/hooks/pre-commit

The patterns look for an AWS access key ID, a private key header, a Stripe-style key, and an assignment such as password = "..." with a long value. They are a starting point, so expect some false alarms and some misses.

Try it. Write a file that contains a key, stage it and commit:

Bash
cat > config.js <<'EOF'
const awsKey = "AKIAIOSFODNN7EXAMPLE";
EOF
git add config.js
git commit -m "Add config" || echo "Commit refused, as intended"

The hook prints pre-commit: this commit adds text that looks like a secret. and Git prints no commit line. The last echo confirms the refusal. AKIAIOSFODNN7EXAMPLE is the example key from AWS's own documentation. Take the file out of the staging area and delete it:

Bash
git restore --staged config.js
rm config.js
git status --short

The status is empty. Hooks live in your local .git/ folder, so they are not shared when others clone the repository. To share a hook, keep it in a committed folder such as .githooks/ and run git config core.hooksPath .githooks on each machine. Dedicated scanners such as gitleaks or trufflehog have far better rules than this hook. Turn on your host's own protection as well. GitHub's push protection, for example, blocks pushes that contain known key formats.

Step 6 · Handle a file you already tracked

A common mistake: you added .env to .gitignore after you had committed it. The ignore rule does nothing for a file Git already tracks. Reproduce it. Your new hook would refuse this commit, because .env holds key-shaped text, so bypass it with --no-verify to recreate the mistake:

Bash
git add -f .env
git commit --no-verify -m "Oops, committed .env"
echo "change" >> .env
git status --short

The status shows M .env: Git still tracks the file and reports the change, despite the ignore rule. Stop tracking it, but keep the file on disk, with git rm --cached:

Bash
git rm --cached .env
git commit -m "Stop tracking .env"
git status --short
git ls-files

The rm line prints rm '.env', and the file stays in your folder. This stops future commits from including it. The secret is still in the older commit, which the next step covers.

Step 7 · When a secret has already been committed

Do these in order. The order matters.

  1. Treat the secret as stolen and replace it first. Revoke the key, change the password, or rotate the token at the service that issued it, then put the new value in your .env. Rewriting history does not help if someone already copied the old one, and a bot can copy it within minutes of a public push. Cleaning up before you rotate leaves the old key working.
  2. Check whether it was used. Look at the provider's access logs or usage page for activity you do not recognise.
  3. Remove it from the history, so it does not keep appearing in clones and searches. The tool the Git project recommends is git filter-repo, which is a separate program. Install it with sudo apt install git-filter-repo on Ubuntu, brew install git-filter-repo on macOS, or pip install git-filter-repo.
Bash
sudo apt install -y git-filter-repo
git filter-repo --version

Work in a fresh clone. As a safety check, git filter-repo refuses to run in a repository that does not look like a fresh clone, and a rewrite cannot be undone, so you keep your working copy as the backup. For a real project you would run git clone <url> secrets-clean with your repository's address. The demo clones the local folder instead, and --no-local makes Git copy the history the way a clone over the network does, rather than sharing files with the original. Rewriting history changes every commit after the secret, so everyone who has a clone must re-clone afterwards. Warn your team first.

Bash
cd ..
git clone --no-local secrets-demo secrets-clean
cd secrets-clean
git filter-repo --invert-paths --path .env

--path .env --invert-paths keeps everything except the file .env, in every commit. Check that the file is gone from the whole history:

Bash
git log --all --oneline -- .env
git log --oneline

The first command prints nothing. The second lists your commits again, with new commit IDs. Then replace the remote history. git filter-repo removes the origin remote on purpose, to stop you pushing by accident, so add it back and force-push:

Bash
git remote add origin git@github.com:you/your-repo.git
git push --force --all origin
git push --force --tags origin

The force-push replaces the branches on the server. Hosts such as GitHub still keep old commits reachable by their ID for a while, and cached copies and forks may keep them. That is why step 1, rotating the secret, is the one that protects you. Ask the host's support to clear cached views if the secret was in a public repository.

Next steps

  • Check what the next commit contains before you make it with git diff --staged.
  • Keep production secrets out of shell history and process lists: prompt for a password instead of typing it on the command line.
  • The official guidance is in the Git documentation for gitignore (man gitignore) and the git-filter-repo project README on GitHub.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.