โšก
Zero to Platform Architect2026
Phase 0: Primitives & Linux

Lesson 3: Git Fundamentals & GitOps Foundations

๐Ÿง  The Concept (Explain Like Iโ€™m 5)

Traditional file saving is like overwriting a word document. If you make a mistake and press save, your past work is gone forever. If two people edit the same file on a shared network drive at the same time, whoever saves last destroys the other personโ€™s work.

Git is a cryptographic time machine and parallel-universe engine:

  • The Cryptographic Snapshot: Instead of saving file diffs or overwriting files, Git takes a complete cryptographic photograph (a Commit) of your entire project directory every time you tell it to.
  • Parallel Universes (Branches): You can branch off from production into an isolated parallel timeline (feature/add-database), build and test new features, and prove they work without touching the live system.
  • Merging Realities: When your feature is verified and approved, you cleanly merge your branch back into the main timeline.
  • The Time Machine: If a bug crashes production at 3:00 AM, you can roll back your entire fleet to the exact commit from 2:59 AM in seconds.

๐Ÿข The Enterprise Context: Why Platform Architects Care

In modern Platform Engineering, Git is the Single Source of Truth (SSOT) for everything that runs in the cloud.

  1. Infrastructure as Code (IaC): Platform teams do not configure AWS, Azure, or GCP by clicking buttons in web consoles. Every VPC, subnet, IAM policy, and database is defined as Terraform or OpenTofu code stored in Git.
  2. GitOps with ArgoCD & Flux: In high-performing platform architectures, human engineers do not have direct write access (kubectl apply) to production Kubernetes clusters. Instead, an automated controller (ArgoCD) monitors your Git repository. When a Pull Request is approved and merged into main, ArgoCD automatically synchronizes the cluster state to match the Git commit.
  3. Auditability & Compliance: Every modification to production infrastructure has an immutable author, timestamp, cryptographic commit signature (GPG/SSH), and associated Pull Request discussion explaining why the change occurred. This satisfies SOC2, ISO 27001, and HIPAA compliance mandates out of the box.
  4. Disaster Recovery (DR): If an entire AWS region experiences a catastrophic outage, an enterprise practicing pure GitOps can spin up an identical cluster in a secondary region simply by pointing ArgoCD at the existing Git repository.

๐Ÿ”ฌ Under the Hood: How Git Actually Works (The Object Database)

Git is not a set of file diffs; Git is a content-addressable key-value object database stored entirely inside the hidden .git/objects directory. Every piece of data is hashed using SHA-1 (40 hexadecimal characters) or SHA-256. The hash of the content is the address of the object.

.git/
โ”œโ”€โ”€ HEAD               # Pointer to current active branch (ref: refs/heads/main)
โ”œโ”€โ”€ config             # Repository-specific configuration
โ”œโ”€โ”€ index              # The Staging Area binary cache
โ”œโ”€โ”€ objects/           # The Object Store (Blobs, Trees, Commits, Tags)
โ”‚   โ”œโ”€โ”€ 4b/825dc6...   # 2-character dir prefix + 38-character filename
โ”‚   โ””โ”€โ”€ info/
โ””โ”€โ”€ refs/
    โ”œโ”€โ”€ heads/         # Local branch pointers (main, dev)
    โ”œโ”€โ”€ remotes/       # Remote tracking branch pointers (origin/main)
    โ””โ”€โ”€ tags/          # Release tags (v1.0.0)

The 4 Core Git Object Types

  1. Blob (Binary Large Object): Contains the raw contents of a file (text, script, image). A blob does not store the file name, directory path, or permissionsโ€”only the byte contents! If two different files in different folders have the exact same contents, Git stores only one blob.
  2. Tree: Represents a directory. A tree object points to blobs (files) and other trees (subdirectories), along with their file names and POSIX permissions (100644 for regular files, 100755 for executables).
  3. Commit: A text manifest containing:
    • A pointer to the top-level root Tree object.
    • A pointer to the Parent Commit(s) (creating the DAG - Directed Acyclic Graph).
    • Author name, email, and timestamp.
    • Committer name, email, and timestamp.
    • The commit message.
  4. Annotated Tag: A permanent pointer to a specific commit containing a tagger, date, message, and optional GPG signature (e.g. v2.4.0-prod).
flowchart TD
    subgraph CommitObject ["Commit: c8f42a1 (Add Webhook)"]
        TreePtr["tree: 91b72e (root)"]
        ParentPtr["parent: a13b8c (init)"]
        Author["author: Alice <alice@corp.com>"]
        Msg["feat: add terraform webhook"]
    end

    subgraph RootTree ["Tree: 91b72e (root directory)"]
        Entry1["100644 blob 3e8a10 (README.md)"]
        Entry2["040000 tree d42f18 (modules/)"]
    end

    subgraph SubTree ["Tree: d42f18 (modules directory)"]
        Entry3["100755 blob 7c91fa (main.tf)"]
        Entry4["100644 blob 12a9e4 (variables.tf)"]
    end

    CommitObject --> RootTree
    RootTree --> Entry1
    RootTree --> SubTree
    SubTree --> Entry3
    SubTree --> Entry4

๐Ÿ—บ๏ธ Visual Architecture: The 4 Zones of Git

Every file on your system moves through four distinct zones during its lifecycle:

flowchart LR
    WD["<b>1. Working Directory</b><br/>Local files on disk<br/>(Unsaved edits)"] -->|"git add &lt;file&gt;"| SA["<b>2. Staging Area (Index)</b><br/>Prepared snapshot<br/>(.git/index)"]
    SA -->|"git commit -m"| LR["<b>3. Local Repository</b><br/>Committed to DAG<br/>(.git/objects)"]
    LR -->|"git push origin"| RR["<b>4. Remote Repository</b><br/>Shared GitHub / GitLab<br/>(origin/main)"]
    RR -->|"git fetch / git pull"| WD
Zone What Lives Here How to Inspect
Working Directory Your actual files on disk where your IDE makes edits git status, file browser
Staging Area (Index) The binary preparation buffer (.git/index) staging changes for the next commit git status -s, git diff --cached
Local Repository The permanent history graph stored in .git/objects on your computer git log --oneline, git show HEAD
Remote Repository The central Git server (GitHub, GitLab, AWS CodeCommit) shared by the entire team git remote -v, git fetch origin

๐ŸŒณ Enterprise Branching: Trunk-Based Development vs. GitFlow

In enterprise cloud infrastructure, traditional GitFlow (with long-running develop, release, and feature branches that live for weeks) leads to catastrophic merge conflicts (โ€œMerge Hellโ€) and slow deployment cycles.

Modern platform engineering standards mandate Trunk-Based Development:

  • All engineers branch directly from main (the โ€œTrunkโ€).
  • Branches are short-lived (lifespan of 1โ€“2 days max).
  • Small, frequent Pull Requests (under 300 lines of code).
  • Automated CI runs automated linting, security scans (Checkov/Trivy), and tests on every PR.
  • Once approved by peer review, PRs merge back into main and trigger automated continuous deployment via GitOps.
gitGraph
    commit id: "Initial Repo"
    commit id: "Base VPC Module"
    branch feature/add-ingress
    checkout feature/add-ingress
    commit id: "Add ALB Manifests"
    commit id: "Add Checkov Policy"
    checkout main
    commit id: "Hotfix DNS TTL"
    checkout feature/add-ingress
    merge main
    checkout main
    merge feature/add-ingress id: "PR-104-Merged"
    commit id: "Release v1.2.0"

โš”๏ธ Merge vs. Rebase: Deep-Dive Comparison

When your feature branch falls behind main, you have two choices to integrate upstream changes:

1. git merge (Preserves History as It Happened)

Creates a new Merge Commit with two parent commits.

  • Pros: Completely non-destructive; exact chronological record of when branches merged.
  • Cons: Creates cluttered, tangled commit graphs with hundreds of meaningless โ€œMerge branch โ€˜mainโ€™ into featureโ€ commits.

2. git rebase (Rewrites History for a Clean Linear Timeline)

Unwinds your feature branch commits, moves the base of your branch to the tip of main, and replays your commits one by one on top.

  • Pros: Produces a crystal-clear, 100% linear history graph that makes git bisect (automated bug hunting) and rollbacks trivial.
  • Cons: Rewrites commit SHAs.

[!CAUTION] The Golden Rule of Rebasing Never rebase a public branch that other people have pulled or are collaborating on! Only rebase your own local feature branches before merging them into main.

flowchart TD
    subgraph MergeModel ["git merge main (Creates 3-way merge commit)"]
        M1["main: commit A"] --> M2["main: commit B"] --> MMerge["Merge Commit M"]
        M1 --> MF1["feat: commit X"] --> MF2["feat: commit Y"] --> MMerge
    end

    subgraph RebaseModel ["git rebase main (Linear replay on tip)"]
        R1["main: commit A"] --> R2["main: commit B"] --> RF1["feat: commit X'"] --> RF2["feat: commit Y'"]
    end

๐Ÿ› ๏ธ Resolving Merge Conflicts Step-by-Step

A merge conflict happens when Git cannot automatically resolve edits because two commits modified the same lines of the same file.

Example Scenario: Conflicting CIDR Blocks in vpc.tf

When Git halts with CONFLICT (content): Merge conflict in vpc.tf, the file contains conflict markers:

<<<<<<< HEAD (Current change on main)
cidr_block = "10.0.0.0/16"
enable_dns_hostnames = true
=======
cidr_block = "10.100.0.0/16"
enable_dns_hostnames = true
>>>>>>> feature/new-vpc (Incoming change from branch)

The Resolution Protocol

# Step 1: Inspect which files are conflicted
git status

# Step 2: Open the file, discuss with the other engineer, and choose the correct value.
# Remove all <<<<<<<, =======, and >>>>>>> markers manually:
# cidr_block = "10.100.0.0/16"
# enable_dns_hostnames = true

# Step 3: Stage the resolved file
git add vpc.tf

# Step 4: Complete the rebase or merge
git rebase --continue
# (Or if merging: git commit -m "fix(vpc): resolve CIDR block conflict")

# If you get completely stuck and want to abort safely:
git rebase --abort
# (Or: git merge --abort)

๐Ÿ”’ Enterprise GitOps Security: Preventing Secret Leaks

Platform engineers frequently handle cloud API keys, SSH private keys, and database passwords. Accidentally committing a secret to Git can compromise an entire enterprise within seconds, as automated botnets constantly crawl public and private repositories.

1. Robust .gitignore for Cloud Engineers

Every repository must contain a strict .gitignore at its root:

# Terraform State & Secrets
*.tfstate
*.tfstate.*
*.tfvars
*.tfvars.json
.terraform/
.terraform.lock.hcl

# Environment & Private Keys
.env
.env.*
!*.env.example
*.pem
*.key
id_rsa
id_ed25519

# Operating System & IDE junk
.DS_Store
.idea/
.vscode/

2. Pre-Commit Hooks (Automated Guardrails)

Install pre-commit to prevent misconfigurations or secrets from ever leaving a developerโ€™s workstation:

# Install framework
pip install pre-commit

# Create .pre-commit-config.yaml
cat << 'EOF' > .pre-commit-config.yaml
repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.5.0
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-yaml
      - id: check-added-large-files
  - repo: https://github.com/trufflesecurity/trufflehog
    rev: v3.63.7
    hooks:
      - id: trufflehog
        entry: trufflehog git file://. --since-commit HEAD --only-verified --fail
EOF

# Activate hooks in local repo
pre-commit install

๐Ÿ’ป Essential Command Cheat Sheet for Platform Engineers

# Branch & Syncing
git checkout -b feature/karpenter-nodepool   # Create and switch to new branch
git status -s                               # Compact status (M=Modified, ??=Untracked)
git add -p                                  # Interactive staging (stage line-by-line)
git commit -S -m "feat(karpenter): add spot nodepool" # GPG-signed commit

# History & Exploration
git log --oneline --graph --decorate -n 15  # Visual branch tree
git diff HEAD~1..HEAD                       # Inspect changes in the latest commit
git blame -L 40,60 main.tf                  # See who wrote each line and why

# Undoing Changes (The Emergency Toolbox)
git restore file.tf                         # Discard unstaged changes in working tree
git restore --staged file.tf                # Unstage file (keep working tree edits)
git commit --amend --no-edit                # Add forgotten staged file into previous commit
git reset --soft HEAD~1                     # Undo last commit, keep code staged
git reset --hard HEAD~1                     # DESTROY last commit and discard all code edits
git stash push -m "wip-debug"               # Stash incomplete edits to switch branches
git stash pop                               # Restore stashed edits

๐Ÿšจ Real-World Troubleshooting & Tricky Production Scenarios

Scenario 1: Accidental Force-Push Overwrites 40 Production Commits

  • Symptom: A developer runs git push --force instead of --force-with-lease after rebasing an out-of-date branch. The remote main branch rewinds by 40 commits, breaking active GitOps deployments and disconnecting in-flight pull requests.
  • Under-the-Hood Root Cause: git push --force ignores the remote tracking ref and forcibly resets the remote branch pointer to the developerโ€™s local commit SHA, detaching un-merged commits from the branch history.
  • Triage & Remediation Runbook:
    # 1. On any team member's machine that fetched recently, find the lost commit SHA via reflog
    git reflog show origin/main
    # Example output: e4a19bc (origin/main) refs/remotes/origin/main@{1}: update: fast-forward
    
    # 2. Re-create the lost branch state locally
    git checkout -b emergency-recovery-main e4a19bc
    
    # 3. Safely push back to origin with lease protection
    git push --force-with-lease origin emergency-recovery-main:main
    
    # 4. Enterprise Guardrail: Enable GitHub/GitLab Branch Protection
    # Rule: Require linear history, block force pushes ('Allow force pushes: disabled')

Scenario 2: Git LFS Pointer Committed Instead of Real Binary Artifact

  • Symptom: A Docker image build fails in CI during RUN ./bin/database_migrate with cannot execute binary file: Exec format error or file not found, even though the file exists locally and works on macOS.
  • Under-the-Hood Root Cause: The developer committed an executable binary tracked under Git LFS (.gitattributes) without running git lfs install. Git committed the 130-byte plain text pointer file (version https://git-lfs.github.com/spec/v1 ...) rather than the multi-megabyte binary. The Linux container attempted to execute the text file as an ELF binary!
  • Triage & Fix:
    # 1. Verify file content on CI runner
    head -n 3 ./bin/database_migrate
    # If output shows "version https://git-lfs.github.com/spec/v1", it's a pointer!
    
    # 2. Pull the true binary content
    git lfs pull
    
    # 3. Add automated pre-commit hook to block pointer commits without LFS hooks installed
    git lfs install --system

๐Ÿ“ Knowledge Check & Real-World Interview Scenarios

โ“ Question 1: The Vanishing Kubectl Edit

An engineer on call encounters a Sev-1 production outage caused by an incorrect database connection string in a Kubernetes Deployment. They run kubectl edit deployment order-service directly in production and fix the value. The service recovers immediately. However, 10 minutes later, the service crashes again with the original bug, and their edit is gone.

What happened, and what is the correct GitOps remediation?

โœ… Answer & Explanation

The Mechanism: The cluster is managed by a GitOps controller (ArgoCD or Flux) configured with Self-Healing and Automated Reconciliation. ArgoCD continuously runs a loop (typically every 3 minutes) comparing the live cluster state with the Git repository (the Single Source of Truth). When the engineer performed a manual kubectl edit, they introduced โ€œConfiguration Driftโ€. ArgoCD detected the drift and automatically overwrote the manual change with the state defined in Git.

The Remediation: In a GitOps architecture, engineers must commit and merge the fix into the Git repository (via a hotfix PR or fast-track pipeline), allowing ArgoCD to synchronize the cluster legitimately.


โ“ Question 2: The Secret Committed in Past Commit

A junior platform engineer committed an AWS IAM Access Key Secret (AKIA...) in a commit three days ago. They realized the error today, made a new commit that deleted the credentials file, and pushed to main.

Is the AWS account safe? Why or why not? What must you do immediately?

โœ… Answer & Explanation

The Answer: The account is NOT safe.

Why: Git is an immutable directed acyclic graph. Deleting a file in a new commit merely records a tree that omits the file; the blob containing the secret key remains permanently stored in .git/objects in the historical commit! Anyone with read access to the repository can run git log -p or git checkout <old-commit> to retrieve the secret key.

Immediate Action:

  1. Immediate Revocation: Immediately delete/deactivate the IAM Access Key in the AWS IAM Console. Never assume a committed secret is safe, even for one second.
  2. History Rewriting: Use git-filter-repo or BFG Repo-Cleaner to rewrite the Git history and purge the blob from all commits, tags, and reflogs.
  3. Force Push: Force-push the sanitized history to all remote branches (git push origin --force --all).