Skip to content
devops.academy

Module 1: Version Control with Git — The Complete Guide

Goal

By the end of this module you'll use Git the way professional engineers do — not just add/commit/push, but recovering from disasters, reviewing code, rebasing safely, and collaborating in teams.

Going deeper

This module is the working knowledge you need day to day. When you want the internals (Git's object model), every command in one place, and a real-world scenario playbook — committed a secret, wrong branch, broken rebase, lost commits — reach for the companion reference: Git In Depth · The Real-World Playbook.


1. Why Version Control Exists (The Real-World Problem)

Imagine you're at a company and a developer says: "The app worked yesterday, but today's deploy broke production." Without version control you'd have folders like project_final_v2_REALLY_FINAL/. With Git you can answer, in seconds:

  • What changed between yesterday and today? (git diff)
  • Who changed it and why? (git blame, git log)
  • Can we go back to yesterday's version right now? (git revert, git checkout)

DevOps relevance: Git isn't just for code. In DevOps, everything lives in Git — Dockerfiles, Kubernetes manifests, Terraform code, CI/CD pipelines. This is called GitOps: Git is the single source of truth for your entire infrastructure. If it's not in Git, it doesn't exist.

Analogy

Working without version control is like playing a long video game with no save feature — one wrong move and hours of progress are gone, so you end up copying the whole game folder before every risky step. Git gives you real save points: every commit is a named moment you can inspect, compare, or return to in seconds.


2. How Git Actually Works (Mental Model)

Git is a snapshot database, not a diff tool. Every commit is a full snapshot of your project, addressed by a SHA-1 hash (e.g., a3f9c21). Understanding the three areas is 80% of understanding Git:

text
Working Directory  →  Staging Area (Index)  →  Repository (.git)
   (your files)         (git add)                (git commit)
  1. Working directory — the files you see and edit.
  2. Staging area — a "shopping cart" of changes you've selected for the next commit.
  3. Repository — the permanent, immutable history stored in .git/.

A branch is just a movable pointer to a commit — creating one costs nothing. HEAD is a pointer to where you currently are.

Analogy

A commit is a save point that captures the entire game world at that instant, not just what changed since the last save. The staging area is where you decide exactly which items make it into the next save before you press the button. A branch is nothing more than a sticky-note bookmark on one save point, and HEAD is the "you are here" arrow — moving a bookmark costs nothing because no game data is copied.

text
main:     A --- B --- C          ← main points at C
                       \
feature:                D --- E  ← feature points at E, HEAD is here

Analogy

Branches are alternate timelines in your save file, and they cost nothing to create. The payment feature lives in one timeline; when the emergency arrives, you hop back to the main timeline, fix the bug there, then jump straight back into your side quest exactly where you left it. Neither timeline ever sees the other's half-finished work until you deliberately merge them.


3. Setup & First Repository

bash
# One-time global config (identity goes into every commit)
git config --global user.name  "Your Name"
git config --global user.email "you@example.com"
git config --global init.defaultBranch main

# Start a repo
mkdir myapp && cd myapp
git init

# Or copy an existing one
git clone https://github.com/user/repo.git

The Daily Core Loop

bash
git status                  # What's changed? Use this constantly.
git add app.py              # Stage one file
git add .                   # Stage everything (use carefully)
git commit -m "Add login endpoint"
git log --oneline --graph   # View history compactly
git diff                    # Unstaged changes
git diff --staged           # What will go into the next commit

Pro habit: run git diff --staged before every commit. Professionals review their own changes before anyone else does.


4. Branching & Merging

Why branches matter

Real scenario: You're building a payment feature (3 days of work). On day 2, a critical production bug arrives. Without branches you'd have half-finished code blocking the fix. With branches:

bash
git switch -c feature/payment    # create + switch (modern syntax)
# ... work happens, bug report arrives ...
git switch main
git switch -c hotfix/login-crash
# fix, commit, merge to main, deploy
git switch feature/payment       # resume, undisturbed

Merging

bash
git switch main
git merge feature/payment

Two merge types:

  • Fast-forward: main hasn't moved; Git just slides the pointer forward. No merge commit.
  • Three-way merge: both branches moved; Git creates a merge commit with two parents.

Merge conflicts (don't panic)

Conflicts happen when two branches change the same lines. Git marks them:

text
<<<<<<< HEAD
port = 8080
=======
port = 3000
>>>>>>> feature/payment

Resolution process: open the file, decide the correct content, delete the markers, then:

bash
git add config.py
git commit          # completes the merge

Real-world tip: conflicts are a communication signal — two people touched the same thing. Talk to the other author if the right answer isn't obvious.


5. Remote Repositories (GitHub Workflow)

Local vs remote: your laptop has a full copy of history; GitHub holds the shared copy. origin is just the default nickname for the remote URL.

bash
git remote -v                          # list remotes
git remote add origin git@github.com:user/repo.git
git push -u origin main                # -u links local main to origin/main
git fetch                              # download remote changes (doesn't touch your files)
git pull                               # fetch + merge in one step
git push                               # upload your commits

fetch vs pull: fetch is safe — it only updates your knowledge of the remote (origin/main). pull also merges into your branch. When in doubt, fetch then inspect with git log origin/main.

Analogy

The remote is the cloud-save server for your game: your laptop keeps a full local copy of every save, and origin is just the nickname of your server slot. A fetch peeks at what the cloud holds without touching your local progress; a pull downloads it and blends it into your current game in one move. Peeking first is always the safer play.

The Pull Request (PR) workflow — how teams actually work

Nobody pushes straight to main in a professional team. The flow is:

text
1. git switch -c feature/user-auth       # branch from latest main
2. ...commit work in small chunks...
3. git push -u origin feature/user-auth
4. Open a Pull Request on GitHub
5. Teammates review, comment, request changes
6. CI pipeline runs tests automatically   ← this is where DevOps begins!
7. Approved → merged into main → deployed

Code review etiquette (both directions):

  • As author: keep PRs small (< ~400 lines reviewable), write a description explaining why, not just what.
  • As reviewer: be specific ("this loop is O(n²), consider a set") not vague ("improve this").
  • main should be protected: no direct pushes, require 1+ approval, require passing CI. As a DevOps engineer, you will configure these branch protection rules.

6. Commit Conventions (Conventional Commits)

Messy history: fix, asdf, more changes. Professional history:

text
feat: add JWT authentication to login endpoint
fix: prevent crash when config file is missing
docs: update deployment instructions
chore: bump nginx image to 1.25
refactor: extract retry logic into helper
ci: add SonarQube scan to pipeline

Format: type(optional-scope): short imperative description

Why it matters in DevOps: tools can parse these to auto-generate changelogs and version numbers (semantic-release). feat → minor version bump, fix → patch, BREAKING CHANGE → major.

Analogy

Compare two save files: one named Save 47, the other labelled "before the dragon fight, full inventory, all potions brewed". Only one of them helps you six months later. Conventional commits are disciplined save-point labels — so consistent that a machine can read the labels and write the changelog for you.


7. Undoing Things (Where Experts Are Made)

The three resets

bash
git reset --soft HEAD~1    # undo commit, keep changes staged
git reset --mixed HEAD~1   # undo commit, keep changes unstaged (default)
git reset --hard HEAD~1    # undo commit, DELETE changes 

Scenario mapping:

  • "I committed too early, want to add one more file" → --soft, add file, recommit.
  • "My last 2 commits should be one" → git reset --soft HEAD~2 then commit once.
  • "This experiment is garbage, wipe it" → --hard (be sure!).

Revert — the safe undo for shared history

reset rewrites history — never do that to commits already pushed to a shared branch. Instead:

bash
git revert a3f9c21    # creates a NEW commit that undoes a3f9c21

Real scenario: a bad commit reached main and broke prod. git revert + push = fastest safe rollback, and the history honestly shows what happened.

Analogy

A reset is reloading an old save and pretending the last hour never happened — fine in a solo game, chaos if your co-op partners already lived through that hour. A revert keeps playing forward: you undo the damage in a brand-new save, so everyone's shared timeline stays intact and the story honestly records both the mistake and the fix.

Reflog — your safety net

git reflog records every position HEAD has been in for ~90 days, even "deleted" commits:

bash
git reset --hard HEAD~3      # oops, destroyed 3 commits!
git reflog                   # find the hash where you were: e.g. b7d2e9a
git reset --hard b7d2e9a     # everything is back

Golden rule: if it was ever committed, it's almost never truly lost.

Analogy

The reflog is the console log of every save you ever made or loaded — including the ones you thought you deleted. Overwrote your progress by mistake? Scroll the log, find the timestamped entry from just before the blunder, and load it. As long as the game saved it once, the game remembers.


8. Rebasing

Rebase replays your commits on top of another branch, producing linear history:

bash
git switch feature/payment
git rebase main        # my commits now sit on top of latest main

Analogy

Rebasing is replaying your side quest on top of the newest chapter of the main story. The outcome looks the same, but the game engine records brand-new save files for every replayed step. That is why you never rebase saves your teammates have already copied — their timeline and yours would suddenly disagree about what happened.

Before:

text
main:     A --- B --- C
                 \
feature:          D --- E

After rebase:

text
main:     A --- B --- C
                       \
feature:                D' --- E'   (new hashes — history rewritten)

Merge vs rebase, practically:

  • Rebase your own feature branch onto main to stay current → clean, linear history.
  • Merge (via PR) to bring the feature into main.
  • The iron rule: never rebase commits that others have already pulled. Rewriting shared history forces everyone into conflict hell.

Interactive rebase — history editing

bash
git rebase -i HEAD~4

Opens an editor where you can pick, squash (combine), reword, drop, or reorder commits. Common use: squash 6 messy "wip" commits into one clean commit before opening a PR.


9. Practical Extras You'll Use Weekly

bash
git stash                  # shelve uncommitted changes temporarily
git stash pop              # bring them back
git cherry-pick <hash>     # copy one commit onto current branch (e.g., hotfix to release branch)
git blame file.py          # who last touched each line, and in which commit
git bisect start           # binary-search history to find which commit broke things
git tag v1.2.0             # mark release points; CI often triggers deploys on tags
.gitignore                 # never commit secrets, node_modules, .env, build artifacts

Security scenario (very real): a developer commits an AWS key in .env. Deleting it in the next commit is NOT enough — it lives in history forever. Correct response: revoke/rotate the key immediately, then scrub history (git filter-repo) if needed. As DevOps, you'll add secret-scanning to CI to catch this before merge.


10. Project Documentation

Every repo needs a README.md that answers: What is this? How do I run it locally? How do I deploy it? Where are the configs?

Minimum professional skeleton:

markdown
# Service Name
One-sentence purpose.

## Prerequisites
- Docker 24+, Make

## Local Development
    make dev        # starts app on :8080

## Deployment
Merges to `main` auto-deploy to staging via GitHub Actions.
Tags matching v* deploy to production.

## Configuration
| Env var        | Purpose            | Default |
|----------------|--------------------|---------|
| DATABASE_URL   | Postgres connection| —       |

11. Hands-On Project (Do This)

  1. Create a GitHub repo devops-git-practice.
  2. Add a README + a small script; commit with conventional messages.
  3. Create feature/improve-docs, make 3 commits, push, open a PR against main.
  4. On another branch, deliberately edit the same line → create and resolve a merge conflict.
  5. Use git reset --hard to destroy a commit, then recover it with reflog.
  6. Squash 3 commits into 1 with git rebase -i.
  7. Enable branch protection on main (require PR + 1 approval).

12. Self-Check Questions

  • What's the difference between git fetch and git pull?
  • Why is reset --hard dangerous on shared branches but revert safe?
  • When would you rebase vs merge?
  • A secret was committed and pushed. What are the correct first steps?
  • What are the three areas of Git and which command moves changes between each?

Next → Module 2: Linux