Platform Engineering · Lesson 05

Git and GitHub Setup: Identity, SSH Keys, .gitignore, and Your First Pull Request

Git records every change to your files as a commit with an author, a message, and a hash; GitHub (or GitLab, or Bitbucket) hosts a shared copy that a team reviews and merges into. Setting both up well takes ten minutes and prevents the two most common early disasters: a secret pushed to a public repository, and a push that fails because GitHub does not know your key. This lesson follows one person from a fresh laptop to a reviewed, merged pull request: identity, sensible defaults, an SSH key for GitHub, a repository with a .gitignore, a commit, a branch, a push, and a review.

Difficulty: Beginner · Know this first: Lesson 04

What you will learn

By the end of this lesson you can work at four levels:

This page teaches it with a plain-language analogy, an animated diagram with normal and failure scenarios, a simulator, a quiz, basic, intermediate, advanced, and master checks, the expert detail ("Go deeper"), a production incident, a hands-on lab with commands and their output, and a production design exercise.

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar adds up minutes from a fresh laptop to a merged first pull request. It is a worked example, not a measurement. The .gitignore and push hops decide whether the change is safe and whether it gets there at all.

Try it: does your first push go well?

Pick whether the repository has a .gitignore, whether your public key is on GitHub, and how you stage files.

23minutes to merged
safe.env
worksgit push

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Git grows in four levels: recording your own work, collaborating on branches, keeping history clean and safe, and running a repository for a team.

Basic — Record your work

At the basic level Git is your undo history.

  • Identity and defaults set once.
  • status, add, commit, and log.
  • A .gitignore before the first commit.

Where it breaks: git add . without reading what it added.

Try it: Basic

Git refuses to commit with "Please tell me who you are". Why?

Now do it: Set your identity and check it.

Intermediate — Collaborate

At the intermediate level you work with others through branches.

  • Branches, push, pull requests, and reviews.
  • An SSH key or credential manager, tested before you need it.
  • Updating your branch from main and resolving conflicts.

Try it: Intermediate

Your pull request has a conflict with main. What do you do?

Now do it: Practise a conflict in a lab repository.

Advanced — Keep history safe

At the advanced level the repository protects itself.

  • Secret scanning and push protection on the host; pre-commit hooks that scan locally.
  • Signed commits; protected main with required reviews and checks.
  • git revert for shared history; never force-push shared branches.

Try it: Advanced

A bad commit is already on main. How do you undo it?

Now do it: Revert a commit in a lab repository.

Master — Run it for a team

At the master level the repository encodes how the team works.

  • Branch protection, CODEOWNERS, and required checks.
  • Templates for pull requests and issues; a contributing guide.
  • Access through teams and single sign-on, reviewed regularly.

Trade-off: required reviews and checks slow every change a little and stop the occasional disaster; tune them so small, safe changes stay fast.

Try it: Master

Why protect the main branch?

Now do it: Check the branch protection on one of your repositories.

Go deeper

A starting global Git configuration (~/.gitconfig), with a separate identity for work repositories:

[user]
    name = Asha Rao
    email = 12345678+asha-rao@users.noreply.github.com
[init]
    defaultBranch = main
[core]
    editor = nano
    autocrlf = input
[pull]
    rebase = false
[includeIf "gitdir:~/work/"]
    path = ~/.gitconfig-work          # sets user.email to the work address

Secret scanning: GitHub's push protection blocks pushes containing many known secret formats; locally, tools such as gitleaks can run as a pre-commit hook. If a secret is pushed: revoke it at its issuer first, replace it, then remove it from history (git filter-repo) and ask the host to purge caches. The order matters, because the secret may already be copied.

HTTPS instead of SSH: gh auth login (the GitHub CLI) or Git Credential Manager stores a token securely. Never write a token into the remote URL, where it ends up in shell history and in .git/config.

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. A demo repository.

Timeline

  • Friday 17:40An engineer publishes a small demo as a public repository with git add . and git push. The folder contains a .env with a cloud access key used for testing.
  • 17:46Automated scanners pick up the key; within the hour, instances appear in an unused region of the cloud account.
  • Saturday 09:00A billing alert fires. The key is revoked, the instances deleted, and the bill disputed with the provider.

What changed after

Push protection and secret scanning on every repository, a pre-commit secret scan in the team template, short-lived credentials instead of long-lived access keys, and budget alerts on every cloud account.

Try it yourself, from scratch

Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.

Before you start: Git 2.32 or newer (git --version; install with sudo apt install -y git or brew install git) and Python 3. A GitHub account is only needed for the last part of the lesson, not for this lab.

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. Set an identity and defaults in a lab-only config file, so your real Git settings stay untouched.

    Reversible

    mkdir -p ~/labs/git-setup && cd ~/labs/git-setup
    export GIT_CONFIG_GLOBAL=~/labs/git-setup/gitconfig
    git config --global user.name "Asha Lab"
    git config --global user.email "asha@example.com"
    git config --global init.defaultBranch main
    git config --global --list

    Options: GIT_CONFIG_GLOBAL tells Git which file to treat as your global config (here a lab file); git config --global key value writes a setting; --list prints them. For your real setup, run the same git config --global lines without the export.

    Expect: user.name=Asha Lab, user.email=asha@example.com, init.defaultbranch=main (Git prints key names in lower case).

    Clean up: The last step removes the folder and unsets the variable; your ~/.gitconfig was never touched.

  2. Create a repository with a .gitignore, an app, and a secret, and watch what Git would commit.

    Reversible

    export GIT_AUTHOR_DATE="2026-01-05T09:00:00Z" GIT_COMMITTER_DATE="2026-01-05T09:00:00Z"
    git init -q -b main app && cd app
    printf '.env\n*.log\n__pycache__/\n' > .gitignore
    printf 'print("hello")\n' > app.py
    printf 'API_KEY=not-a-real-key\n' > .env
    git status --short
    git add . && git status --short

    Options: The two date variables fix the commit time so your hashes match the page; git status --short prints ?? for untracked files and A for files staged to be added.

    Expect: Before adding: ?? .gitignore and ?? app.py. After git add .: A .gitignore and A app.py. .env never appears, because the .gitignore excludes it.

    If it fails: If .env shows up, the .gitignore is missing or misspelt; git rm --cached .env unstages it without deleting the file.

  3. Commit, and ask Git which rule keeps .env out.

    Reversible

    git commit -q -m "First commit" && git log --oneline
    git check-ignore -v .env

    Options: -q quiet; -m the message; git check-ignore -v prints the file, line, and pattern that ignore a path.

    Expect: b3646ff First commit (the same hash as here, thanks to the fixed dates, name, and email), then .gitignore:1:.env and .env.

  4. A branch, a change, and a merge back into main.

    Reversible

    git switch -q -c feature/greeting
    printf 'print("hello, team")\n' > app.py
    git commit -qam "Friendlier greeting"
    git switch -q main && git merge -q feature/greeting && git log --oneline --graph

    Options: git switch -c creates a branch and moves to it; commit -a stages changed tracked files; merge brings the branch's commits into the current branch.

    Expect: * e8f6d60 Friendlier greeting above * b3646ff First commit: main fast-forwarded to the branch.

  5. Add a remote, the way you would before the first push. Nothing is contacted.

    Reversible

    git remote add origin git@github.com:example/app.git
    git remote -v

    Expect: origin git@github.com:example/app.git (fetch) and the same with (push). With your own repository, ssh -T git@github.com first, then git push -u origin main. Those two need a GitHub account and key, so this lab does not run them.

  6. Clean up.

    Potentially destructive

    cd ~ && rm -rf ~/labs/git-setup
    unset GIT_CONFIG_GLOBAL GIT_AUTHOR_DATE GIT_COMMITTER_DATE
    ls ~/labs

    Expect: No error; git-setup is gone, and new shells use your normal Git config again.

2. Python: staged_check.py

This program is a tiny pre-commit check: given the files about to be committed and their contents, it flags names that should be ignored and contents that look like secrets, the way secret-scanning tools do, before anything leaves your machine. Save it as staged_check.py, then run it.

# staged_check.py
import re

STAGED = {
    "app.py": 'print("hello")\n',
    "config/settings.py": 'DEBUG = False\nTIMEOUT = 30\n',
    ".env": "API_KEY=sk_live_51HbQ2xEXAMPLEonly7Zq\n",
    "deploy/key.pem": "-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAA\n-----END OPENSSH PRIVATE KEY-----\n",
    "notes.txt": "call the vendor about the token rotation\n",
}
NEVER = [r"(^|/)\.env$", r"\.pem$", r"(^|/)id_(rsa|ed25519)$", r"\.log$"]
SECRETS = {
    "private key": r"-----BEGIN [A-Z ]*PRIVATE KEY-----",
    "live API key": r"\bsk_live_[0-9A-Za-z]{16,}",
    "AWS access key ID": r"\bAKIA[0-9A-Z]{16}\b",
}

problems = 0
for name, text in STAGED.items():
    bad_name = any(re.search(p, name) for p in NEVER)
    found = [label for label, p in SECRETS.items() if re.search(p, text)]
    if bad_name or found:
        problems += 1
        why = ", ".join((["file name should be in .gitignore"] if bad_name else []) + found)
        print(f"BLOCK  {name:<20} {why}")
    else:
        print(f"ok     {name}")
print()
print(f"{problems} file(s) blocked:", "unstage them (git rm --cached FILE) and add them to .gitignore" if problems else "safe to commit")

Run it, and you should see this output:

$ python3 staged_check.py
ok     app.py
ok     config/settings.py
BLOCK  .env                 file name should be in .gitignore, live API key
BLOCK  deploy/key.pem       file name should be in .gitignore, private key
ok     notes.txt

2 file(s) blocked: unstage them (git rm --cached FILE) and add them to .gitignore

3. What to notice

4. Advanced: every step as one Bash script

The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/git-and-github-setup-identity-ssh-keys-and-first-repository && cd ~/labs/git-and-github-setup-identity-ssh-keys-and-first-repository) and save this as lab.sh.

#!/usr/bin/env bash
# The Linux steps of "Git and GitHub Setup: Identity, SSH Keys, .gitignore, and Your First Pull Request", as one script (save it as lab.sh).
#
#   ./lab.sh          run every step, in order
#   ./lab.sh 2 4      run only steps 2 and 4
#   ./lab.sh --list   list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.

STEPS=(
  'Set an identity and defaults in a lab-only config file, so your real Git settings stay untouched.'
  'Create a repository with a .gitignore, an app, and a secret, and watch what Git would commit.'
  'Commit, and ask Git which rule keeps .env out.'
  'A branch, a change, and a merge back into main.'
  'Add a remote, the way you would before the first push. Nothing is contacted.'
  'Clean up.'
)

step_1() {
mkdir -p ~/labs/git-setup && cd ~/labs/git-setup
export GIT_CONFIG_GLOBAL=~/labs/git-setup/gitconfig
git config --global user.name "Asha Lab"
git config --global user.email "asha@example.com"
git config --global init.defaultBranch main
git config --global --list
}

step_2() {
export GIT_AUTHOR_DATE="2026-01-05T09:00:00Z" GIT_COMMITTER_DATE="2026-01-05T09:00:00Z"
git init -q -b main app && cd app
printf '.env\n*.log\n__pycache__/\n' > .gitignore
printf 'print("hello")\n' > app.py
printf 'API_KEY=not-a-real-key\n' > .env
git status --short
git add . && git status --short
}

step_3() {
git commit -q -m "First commit" && git log --oneline
git check-ignore -v .env
}

step_4() {
git switch -q -c feature/greeting
printf 'print("hello, team")\n' > app.py
git commit -qam "Friendlier greeting"
git switch -q main && git merge -q feature/greeting && git log --oneline --graph
}

step_5() {
git remote add origin git@github.com:example/app.git
git remote -v
}

step_6() {
cd ~ && rm -rf ~/labs/git-setup
unset GIT_CONFIG_GLOBAL GIT_AUTHOR_DATE GIT_COMMITTER_DATE
ls ~/labs
}

# print a step that has to be run by hand, instead of running it
by_hand() {
  echo "  (run this one yourself: $1)"
  sed 's/^/    /'
}

RESULTS=()
run_step() {
  local n=$1 start=$SECONDS code
  printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
  "step_$n"
  code=$?
  RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}

summary() {
  echo
  echo "== summary"
  local r
  for r in "${RESULTS[@]}"; do echo "  $r"; done
}

case "${1:-}" in
  -h|--help) sed -n '2,6p' "$0"; exit 0 ;;
  --list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac

[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
  if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
    echo "there is no step '$n'; try --list" >&2
    exit 2
  fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done

Then make it executable and run it:

chmod +x lab.sh
./lab.sh --list     # the steps
./lab.sh            # every step, then a summary of exit codes and times
./lab.sh 2 3        # only steps 2 and 3

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

You are setting up the Git workflow for a new team of six with a mix of new and experienced engineers. Design the setup guide and repository rules.

Clarifying questions to ask

What does each person configure? How do they authenticate to the host? What goes in every repository from day one? How are secrets kept out? What are the rules for main? How is a bad change undone?

Rough sizing

Say six engineers, 10 repositories, and about 40 pull requests a week.

Shape of the answer

A setup guide with identity, defaults, an SSH key tested with ssh -T or gh auth login; a repository template with .gitignore, a pre-commit secret scan, a pull request template, and CODEOWNERS; push protection and secret scanning on; main protected with one review and passing CI; git revert for undoing changes on main; a written procedure for leaked secrets that starts with revoking them.

Trade-offs to name

Required reviews add waiting time to every change; pairing, small pull requests, and clear owners keep that wait short.

Failure modes and how to troubleshoot them

Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.

ScenarioWhereEffectWhat goes wrong
Secret pushedHop 5: .gitignoreBreaksNo .gitignore. The project has a .env file with a real payment-provider API key for local testing. git add . stages it with everything else; nobody reads the staged list.
Secret pushedHop 6: CommitBreaksThe commit contains app.py and .env.
Secret pushedHop 8: PushBreaksPushed to a public repository. Within minutes an automated scanner finds the key; the payment provider's own scanning flags it too.
Push rejectedHop 3: SSH keyDegradesKey generated; the public half was never pasted into GitHub, and ssh -T was not run.
Push rejectedHop 8: PushBreaksgit@github.com: Permission denied (publickey). fatal: Could not read from remote repository. The key is not on GitHub and the agent has nothing loaded. 25 minutes of searching end with ssh -T git@github.com, which says the same thing in one line.

How to troubleshoot

  1. Write down the symptom and when it started: what users see, which number moved, and what changed just before (a deploy, a config change, traffic).
  2. Walk the path in order, from the first hop to the last: Identity → Defaults → SSH key → Repository → .gitignore → Commit → Branch → Push → Review. The first hop whose evidence is wrong is where to dig.
  3. At that hop, run the read-only check from the diagram or the lab first; change nothing until the evidence points at a cause.
  4. Fix the smallest thing that restores service, or roll back the last change, and confirm the symptom is gone with the same check.
  5. Write down what you found and the check that would have caught it sooner, so the next person starts there.

References and review

The official documentation and standards behind this lesson. Versions and defaults change; when a command or field here differs from them, trust the official page.

Last updated . Next review due by November 2027. Found something out of date? Tell me.

Saved on this device, in this browser.
Next in this series · Lesson 06
Python Setup: Versions, Virtual Environments, pip, and Pinned Requirements

Your operating system already has a Python, and it belongs to the operating system: system tools depend on the exact packages it has. So every project gets its own virtual environment, a private folder with its own Python and its…

Go to Lesson 06 →

Or browse the full course from the Lessons index.