Chapter 2 · Git and GitHub
.gitignore: Keeping Secrets and Junk Out
- Page 6 of 22
- 17 min read
An AI project folder fills up fast with things that must never go into Git: an .env file holding your OpenAI or Anthropic API key, a .venv folder with thousands of library files, __pycache__ leftovers, a 2 GB training CSV, a trained model file, notebook checkpoints. Commit any of them and you get a slow, bloated repository at best, and a leaked API key that someone runs up a bill on at worst.
The tool that prevents this is one small text file, .gitignore. This page shows you how to write one for an AI project, how to check what it really does, what to do when something is already committed, and why a secret that ever reached a commit has to be treated as leaked.
What you will learn
- What
.gitignoredoes, and the pattern rules: names, folders,*,**, a leading/, and!exceptions. - A practical
.gitignorefor AI projects:.env,.venv,__pycache__, data, model files, notebook checkpoints. - The
.env+.env.examplepattern, so teammates know which settings to provide without seeing yours. - Debugging rules with
git check-ignore -vandgit status --ignored. - Untracking a file that was already committed (
git rm --cached), and why a committed secret is a leaked secret.
Set up the example project
Every page in this chapter starts from an empty home folder, so first build a tiny project: a keyword-based review sentiment analyser with a few sample reviews. You know every command here from the previous two pages; -q (quiet) just keeps git init and git commit from printing their usual messages. On day one Nadia also saved her first "trained model" in models/ and committed it, before she knew better. (The model file is a stand-in: a few bytes instead of real weights.)
mkdir -p ~/projects/review-analyser
cd ~/projects/review-analyser
git init -q
cat > analyse.py <<'EOF'
"""Label product reviews as positive, negative or neutral with two small word lists."""
import csv
POSITIVE = {"good", "great", "fast", "love", "excellent"}
NEGATIVE = {"bad", "slow", "broken", "late", "terrible"}
def label(text):
words = text.lower().split()
score = sum(w in POSITIVE for w in words) - sum(w in NEGATIVE for w in words)
return "positive" if score > 0 else "negative" if score < 0 else "neutral"
if __name__ == "__main__":
with open("reviews.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
print(label(row["text"]), "|", row["text"])
EOF
cat > reviews.csv <<'EOF'
id,text
1,great phone and fast delivery
2,battery is bad and the box was broken
3,it works
EOF
mkdir -p models
printf 'stand-in for trained weights v1\n' > models/sentiment-v1.joblib
git add .
git commit -q -m "Add keyword review analyser, sample reviews and first model"
python analyse.pypositive | great phone and fast delivery
negative | battery is bad and the box was broken
neutral | it worksThe mess a real AI project makes
Now let the project grow the way real ones do. Each line below creates something you will meet in almost every AI repository:
python -m venv .venv # a virtual environment (thousands of files)
rm -f .venv/.gitignore # Python 3.13+ adds this file; see the note below
python -m py_compile analyse.py # what importing does: creates __pycache__/
mkdir -p data/raw data/sample notebooks/.ipynb_checkpoints
python -c "
rows = ['id,text'] + [f'{i},sample review {i}' for i in range(1, 200001)]
open('data/raw/reviews-full.csv', 'w').write('\n'.join(rows) + '\n')
"
head -n 3 data/raw/reviews-full.csv > data/sample/reviews-sample.csv
echo '{"cells": []}' > notebooks/explore.ipynb
echo '{"cells": []}' > notebooks/.ipynb_checkpoints/explore-checkpoint.ipynb
cat > .env <<'EOF'
OPENAI_API_KEY=sk-proj-EXAMPLE-not-a-real-key
DATABASE_URL=postgresql://nadia:[email protected]/reviews
EOF
git statusOn branch main
Untracked files:
(use "git add <file>..." to include in what will be committed)
.env
.venv/
__pycache__/
data/
notebooks/
nothing added to commit but untracked files present (use "git add" to track)Git sees five untracked entries, and only a small part of them (the notebook and the data sample) belongs in the repository. A single careless git add . now would commit your API key, a 4 MB data file and a whole Python installation. (The model file is not listed because it is already tracked; it shows up again later.) wc shows how big the "real" data already is:
wc -l data/raw/reviews-full.csv200001 data/raw/reviews-full.csvAbout
.venv: since Python 3.13,python -m venv(anduv venv) writes a one-line.gitignorecontaining*inside the new environment, so Git ignores it on its own. We deleted that file above so everyone sees the same output, whatever their Python. Still put.venv/in your project's.gitignore: older Pythons,virtualenvand conda environments do not add one.
Writing a .gitignore
A .gitignore is a plain text file in the root of the repository, one pattern per line. Git skips untracked files that match a pattern: they disappear from git status and git add . will not pick them up. The file itself is committed, so every teammate and every clone gets the same rules. Create it in your editor (the first line is a comment):
# file: .gitignore
# Secrets: never commit these
.env
.env.*
!.env.example
# Python
__pycache__/
*.py[cod]
.venv/
venv/
# Jupyter
.ipynb_checkpoints/
# Data and models: too big for Git, stored and versioned elsewhere
data/*
!data/sample/
models/
*.joblib
*.pt
*.safetensorsgit statusOn branch main
Untracked files:
(use "git add <file>..." to include in what will be committed)
.gitignore
data/
notebooks/
nothing added to commit but untracked files present (use "git add" to track)Now only three things are left: the .gitignore itself, data/ (because of the data/sample/ exception) and notebooks/ (because of explore.ipynb). The secrets, the environment, the bytecode, the big CSV and the checkpoint copies are gone from view. Notice what is not there either: models/sentiment-v1.joblib. It matches models/, but it was committed before the rule existed. Keep that in mind; we come back to it below.
The pattern rules
| Pattern | Matches | Example use |
|---|---|---|
.env | A file or folder with that name, in any folder | Secrets file |
models/ | A trailing / means folders only (and everything in them) | Model checkpoints |
*.joblib | * is any run of characters except / | Saved scikit-learn models anywhere |
*.py[cod] | [cod] is one character from the set: .pyc, .pyo, .pyd | Compiled Python |
/output.csv | A leading / anchors to the folder of the .gitignore (here, the root only) | A file the script writes in the root |
data/* | Everything directly inside data/ (a / in the middle also anchors the pattern) | Raw data |
**/checkpoints/ | ** means "any number of folders" | Checkpoint folders at any depth |
!.env.example | ! re-includes something an earlier pattern excluded | The settings template |
# text | A comment; blank lines are ignored too | Explaining a rule |
Two rules decide the tricky cases. First, the last matching pattern wins, which is why !.env.example comes after .env.*. Second, Git cannot re-include a file if its parent folder is excluded: with data/ it never even looks inside the folder, so !data/sample/ would do nothing. That is why the file says data/* (ignore the contents of data/) and then makes an exception for data/sample/.
Checking what is ignored, and why
When a file is ignored and you don't know why (or is not ignored and should be), ask Git. git check-ignore -v prints the file, line number and pattern that decided:
git check-ignore -v .env data/raw/reviews-full.csv .venv __pycache__ notebooks/.ipynb_checkpoints.gitignore:3:.env .env
.gitignore:17:data/* data/raw/reviews-full.csv
.gitignore:10:.venv/ .venv
.gitignore:8:__pycache__/ __pycache__
.gitignore:14:.ipynb_checkpoints/ notebooks/.ipynb_checkpointsA file that is not ignored prints nothing, and the command exits with status 1. Add -n (--non-matching) to see it listed anyway:
git check-ignore -v -n data/sample/reviews-sample.csv .env.example:: data/sample/reviews-sample.csv
.gitignore:5:!.env.example .env.example:: means "no pattern matches this file": the sample is not ignored at all, because the !data/sample/ exception keeps its folder in play. .env.example matched a pattern, but it is the ! exception on line 5, and a pattern starting with ! means "do not ignore". For the whole picture, git status --ignored lists ignored files too; in short form, ?? means untracked and !! means ignored:
git status --short --ignored?? .gitignore
?? data/
?? notebooks/
!! .env
!! .venv/
!! __pycache__/
!! data/raw/
!! notebooks/.ipynb_checkpoints/Git also guards against accidents. If you name an ignored file explicitly, git add refuses:
git add .envThe following paths are ignored by one of your .gitignore files:
.env
hint: Use -f if you really want to add them.
hint: Turn this message off by running
hint: "git config advice.addIgnoredFile false"git add -f would force it in. For a secrets file the answer is simply: don't.
.env and .env.example
Your code needs the real settings, but the repository must not contain them. The standard answer, which you met in Environment Variables, .env Files and Virtual Environments, has two files:
.env: the real values on your machine. Ignored, never shared through Git..env.example: the same variable names with placeholder values. Committed, so a teammate (or you on a new laptop) knows what to fill in:cp .env.example .env, then edit.
cat > .env.example <<'EOF'
# Copy to .env and fill in real values. Never commit .env.
OPENAI_API_KEY=your-key-here
DATABASE_URL=postgresql://user:password@localhost/reviews
EOF
git check-ignore -q .env.example || echo ".env.example will be committed"
git check-ignore -q .env && echo ".env stays private".env.example will be committed
.env stays private(-q prints nothing and only sets the exit status, handy in scripts.) The program reads the real values from the environment, never from the source code. With python-dotenv, load_dotenv(".env") copies the values from the file into os.environ (called with no path, it looks for .env starting from the script's own folder):
import os
from dotenv import load_dotenv
load_dotenv(".env") # copies the values into os.environ
key = os.environ["OPENAI_API_KEY"]
print("key loaded:", key[:8] + "...") # never print or log a whole keykey loaded: sk-proj-...Now stage everything and look at what would be committed. Thanks to the rules, git add . is safe again:
git add .
git status --shortA .env.example
A .gitignore
A data/sample/reviews-sample.csv
A notebooks/explore.ipynbgit commit -m "Ignore secrets, environments, data and models; add .env.example"[main 7155cf8] Ignore secrets, environments, data and models; add .env.example
4 files changed, 29 insertions(+)
create mode 100644 .env.example
create mode 100644 .gitignore
create mode 100644 data/sample/reviews-sample.csv
create mode 100644 notebooks/explore.ipynbAlready committed? .gitignore will not help
.gitignore only affects untracked files. A file Git already tracks stays tracked, whatever the rules say. Watch: Nadia retrains her model, and Git reports the change even though models/ is in .gitignore:
printf 'stand-in for trained weights v2\n' > models/sentiment-v1.joblib
git status --short M models/sentiment-v1.joblibTo stop tracking it, remove it from the index (the staging area) but not from the disk, with git rm --cached, and commit that:
git rm --cached models/sentiment-v1.joblib
git commit -q -m "Stop tracking model files"
ls models
git status --short
git check-ignore -v models/sentiment-v1.joblibrm 'models/sentiment-v1.joblib'
sentiment-v1.joblib
.gitignore:19:models/ models/sentiment-v1.joblibThe file is still on disk, Git no longer tracks it, and from now on the models/ rule keeps it out. For a whole folder use git rm -r --cached models/. One warning: when a teammate pulls this commit, Git deletes their copy of the file, because from Git's point of view it was removed. Tell the team, and keep model files somewhere meant for them (a shared drive, cloud storage, Git LFS or DVC, which the advanced tutorial covers).
And the old version is still in history. Anyone who clones the repository downloads it, forever:
git log --oneline -- models/sentiment-v1.joblib095aca1 Stop tracking model files
7a92438 Add keyword review analyser, sample reviews and first modelFor a small model file that is merely wasteful. For a secret it is a disaster.
A committed secret is a leaked secret
Here is the mistake every developer makes once. Nadia is in a hurry, pastes her key straight into the code to "test quickly", and commits:
cat > llm_client.py <<'EOF'
API_KEY = "sk-proj-EXAMPLE-not-a-real-key"
EOF
git add llm_client.py
git commit -q -m "Add LLM client"She notices, reads the key from the environment instead, and commits the fix:
cat > llm_client.py <<'EOF'
import os
API_KEY = os.environ["OPENAI_API_KEY"]
EOF
git commit -q -am "Read the API key from the environment"
cat llm_client.pyimport os
API_KEY = os.environ["OPENAI_API_KEY"]The current file is clean. But a commit is a snapshot, and the old snapshot is still there. Anyone with a copy of the repository can search every version ever committed (-S finds commits that added or removed a string) and print the old file:
git log --oneline -S "sk-proj"
git show HEAD~1:llm_client.pyb396fd5 Read the API key from the environment
d7ccc6d Add LLM client
API_KEY = "sk-proj-EXAMPLE-not-a-real-key"If this repository was ever pushed to GitHub, assume the key is in someone else's hands: bots scan public repositories for keys within minutes. The order of what to do is:
- Revoke or rotate the key first, in the provider's dashboard (OpenAI, Anthropic, AWS, your database). This is the only step that actually stops the damage. Check the usage and billing page for activity you don't recognise.
- Then remove it from history, if you need to. That rewrites commits (
git filter-repo), which the Advanced tutorial teaches with the precautions it needs. Deleting the line in a new commit, as Nadia did, is not enough. - Prevent the next one:
.envin.gitignorefrom the first commit, keys only through environment variables, and a secret scanner.
GitHub helps here. Secret scanning runs automatically and for free on public repositories, and push protection, on by default for public repositories, blocks a git push that contains a recognised key (OpenAI, Anthropic, AWS, GitHub tokens and many more) and tells you which commit and line it found. Treat these as a seat belt, not a reason to be careless: they only know the key formats they know, and a private repository on the free plan does not get the same protection.
Three places to put ignore rules
| Where | Shared? | Use it for |
|---|---|---|
.gitignore in the repository (there can be more in subfolders) | Yes, committed | Everything the project creates: .env, .venv/, data, models, build output |
A global file set with core.excludesFile | No, your machine only | Your editor and operating system: .vscode/, .idea/, .DS_Store, Thumbs.db |
.git/info/exclude | No, this one repository only | Personal scratch files in one project |
Setting up the global file once saves you from adding your editor's folders to every project:
printf '.DS_Store\nThumbs.db\n.idea/\n' > ~/.gitignore_global
git config --global core.excludesFile ~/.gitignore_global
touch .DS_Store
git check-ignore -v .DS_Store/home/nadia/.gitignore_global:1:.DS_Store .DS_StoreYou don't have to invent a project .gitignore from nothing either. GitHub's collection at github.com/github/gitignore has a well-maintained Python.gitignore, and GitHub offers it as a template when you create a repository. Start from it, then add your data, model and notebook rules.
Where this shows up in real AI work
- Every LLM app has provider keys. Teams keep them in
.envlocally, in GitHub Actions secrets for CI and in the hosting platform's settings in production; the repository only ever holds.env.example. - Datasets and model weights live outside Git: object storage (S3, Google Cloud Storage), the Hugging Face Hub, Git LFS or DVC. The repository holds the code, a small sample for tests, and a script or pointer to fetch the rest.
- Experiment outputs (
runs/,wandb/,mlruns/,outputs/) are usually ignored; results that matter are logged to an experiment tracker instead. - Leaked keys are a real cost. A key found by a bot can be used to run thousands of LLM requests on your account within hours, which is why providers and GitHub scan for them.
Common mistakes
- Adding
.gitignoreafter the firstgit add .. The files are already tracked and the rules do nothing for them. Fix: write.gitignorebefore the first commit; if it is too late,git rm --cachedthe files and commit. - Ignoring a folder and then trying to re-include something inside it.
data/followed by!data/sample/does nothing, because Git never looks inside an excluded folder. Fix:data/*then!data/sample/, and check withgit check-ignore -v. - Thinking a new commit removes a secret. The key is still in every earlier commit and in every clone. Fix: rotate the key first, then clean history if needed.
- Committing
.env"just for the team". Anyone with read access, now or later (a contractor, a public fork, a leaked laptop), gets production credentials. Fix: commit.env.exampleand share real values through a password manager or the platform's secrets settings. - Ignoring too much. A rule like
*.jsonalso hidespackage.jsonor a config file the app needs, and a teammate's clone breaks. Fix: write narrow rules, and look atgit status --ignoredonce in a while.
Try it yourself
Do these in the review-analyser repository, in order.
- Easy: Your training script writes
training.login the root and more logs inlogs/. Createtraining.logandlogs/run-01.log, add one rule that ignores all.logfiles, and prove it withgit check-ignore -v. - Medium: Predictions are saved to
outputs/, but the folder'soutputs/README.md, which explains the file format, should be committed. Write rules that ignore everything inoutputs/except that README, createoutputs/README.mdandoutputs/predictions.csv, and show withgit status --short --untracked-files=all(which lists files inside new folders) that only the README is offered. - Hard: A teammate committed
secrets.jsoncontaining a token. Create and commit that file to simulate it, then stop tracking it without deleting it from disk, make sure it stays ignored, and list the commits whose snapshots contain it. What must happen to the token itself?
Answers
# Easy
touch training.log
mkdir -p logs && touch logs/run-01.log
echo '*.log' >> .gitignore
git check-ignore -v training.log logs/run-01.log.gitignore:23:*.log training.log
.gitignore:23:*.log logs/run-01.log# Medium
printf 'outputs/*\n!outputs/README.md\n' >> .gitignore
mkdir -p outputs
echo '# Prediction files: one CSV per run' > outputs/README.md
echo 'id,label' > outputs/predictions.csv
git status --short --untracked-files=all M .gitignore
?? outputs/README.mdOnly .gitignore (changed) and outputs/README.md are offered; predictions.csv is ignored. Commit both so the rules are shared:
git add .gitignore outputs/README.md
git commit -q -m "Ignore logs and prediction outputs"# Hard
echo '{"hf_token": "hf_EXAMPLEnotARealToken"}' > secrets.json
git add secrets.json
git commit -q -m "Add config"
git rm -q --cached secrets.json
echo 'secrets.json' >> .gitignore
git add .gitignore
git commit -q -m "Stop tracking secrets.json"
ls secrets.json
git check-ignore -v secrets.json
git log --oneline --all -- secrets.jsonsecrets.json
.gitignore:26:secrets.json secrets.json
03a9ec9 Stop tracking secrets.json
908189b Add configThe log shows the commit that added it and the one that stopped tracking it; the first one still contains the token. The token must be revoked and replaced on the provider's site (here, Hugging Face). Removing the old commit from history comes after that and is optional cleanup, not the fix.
Summary
.gitignorelists patterns for untracked files Git should skip; it is committed, so the whole team shares it. The last matching pattern wins, and!makes exceptions.- For AI projects, ignore at least
.env,.venv/,__pycache__/,.ipynb_checkpoints/, raw data and model files; commit.env.exampleand a small data sample. git check-ignore -vtells you which rule matched;git status --short --ignoredshows everything that is ignored.- Rules don't apply to files already tracked:
git rm --cachedstops tracking without deleting, and the old versions stay in history. - A secret that reached a commit is leaked: rotate it first, then clean history (advanced tutorial). GitHub's secret scanning and push protection are a safety net, not a plan.
Next: Undoing Mistakes: restore, reset and revert. You will learn how to throw away a bad edit, unstage a file, fix the last commit, and undo a commit safely, both before and after you have shared it.

