DevOps Week 3: Complete Git Mastery Guide

Dev DaveDev Dave
8 min read

A comprehensive documentation of Git fundamentals, advanced operations, and DevOps integration


๐ŸŽฏ Introduction

This documentation covers Week 3 of the TechWorld with Nana DevOps Bootcamp, focusing on mastering Git for version control and DevOps workflows. This guide serves as both a learning resource and reference material for Git operations in professional environments.

Learning Objectives

  • Master Git fundamentals and architecture

  • Implement effective branching strategies

  • Perform advanced Git operations confidently

  • Apply Git best practices in team environments

  • Integrate Git into DevOps workflows


๐Ÿ”ง Git Fundamentals

What is Git?

Git is a distributed version control system that tracks changes in source code during software development. Unlike centralized systems, Git allows every developer to have a complete history of the project.

Key Concepts

Repository Structure

.git/
โ”œโ”€โ”€ HEAD
โ”œโ”€โ”€ config
โ”œโ”€โ”€ objects/
โ”œโ”€โ”€ refs/
โ””โ”€โ”€ index

Git Workflow States

  1. Working Directory: Where you edit files

  2. Staging Area: Where you prepare commits

  3. Repository: Where commits are stored

bash# The basic Git workflow
git add .           # Working Directory โ†’ Staging Area
git commit -m "..."  # Staging Area โ†’ Repository  
git push origin main # Repository โ†’ Remote Repository

Initial Setup

bash# Global configuration
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"

# Per-repository configuration
git config user.name "Project Name"
git config user.email "project@example.com"

๐Ÿ—‚๏ธ Repository Management

Creating Repositories

Initialize Local Repository

bash# Create new repository
git init

# Initialize with specific branch name
git init --initial-branch=main

Clone Remote Repository

bash# Clone repository
git clone https://github.com/user/repo.git

# Clone with specific branch
git clone -b develop https://github.com/user/repo.git

Remote Repository Management

Adding Remotes

bash# Add remote origin
git remote add origin https://github.com/user/repo.git

# Add multiple remotes
git remote add upstream https://github.com/original/repo.git
git remote add origin https://github.com/yourusername/repo.git

Remote Operations

bash# List remotes
git remote -v

# Remove remote
git remote remove origin

# Change remote URL
git remote set-url origin https://new-url.git

๐ŸŒฟ Branching Strategies

Understanding Branches

Branches allow parallel development without affecting the main codebase.

bash# List all branches
git branch -a

# Create new branch
git branch feature/user-authentication

# Switch to branch
git checkout feature/user-authentication

# Create and switch in one command
git checkout -b feature/user-authentication

Common Branching Models

Git Flow

main (production)
โ”œโ”€โ”€ develop (integration)
    โ”œโ”€โ”€ feature/user-auth
    โ”œโ”€โ”€ feature/payment-system
    โ””โ”€โ”€ hotfix/critical-bug

GitHub Flow

main (production)
โ”œโ”€โ”€ feature/user-auth
โ”œโ”€โ”€ feature/payment-system
โ””โ”€โ”€ hotfix/critical-bug

Merge Strategies

Merge Commit

bashgit checkout main
git merge feature/user-auth

Fast-Forward Merge

bashgit checkout main
git merge --ff-only feature/user-auth

Squash Merge

bashgit checkout main
git merge --squash feature/user-auth
git commit -m "Add user authentication system"

โšก Advanced Git Operations

Rebase Operations

Interactive Rebase

bash# Rebase last 3 commits
git rebase -i HEAD~3

# Rebase onto main
git rebase main

Rebase Options

  • pick: Use commit as-is

  • reword: Edit commit message

  • edit: Edit commit content

  • squash: Combine with previous commit

  • drop: Remove commit

Stash Operations

Basic Stash

bash# Stash current changes
git stash

# Stash with message
git stash push -m "WIP: user authentication"

# List stashes
git stash list

# Apply stash
git stash apply

# Apply and remove stash
git stash pop

Advanced Stash

bash# Stash specific files
git stash push -m "partial work" file1.js file2.js

# Stash including untracked files
git stash -u

# Create branch from stash
git stash branch feature/stash-branch stash@{0}

History Navigation

Checkout Operations

bash# Checkout specific commit
git checkout abc123

# Checkout specific file from commit
git checkout abc123 -- file.txt

# Checkout branch
git checkout main

Reset Operations

bash# Soft reset (keep changes staged)
git reset --soft HEAD~1

# Mixed reset (keep changes unstaged)
git reset --mixed HEAD~1

# Hard reset (discard changes)
git reset --hard HEAD~1

๐Ÿ›ก๏ธ Best Practices

Commit Guidelines

Commit Message Format

<type>(<scope>): <subject>

<body>

<footer>

Examples

bashgit commit -m "feat(auth): add user authentication system"
git commit -m "fix(api): resolve null pointer exception in user service"
git commit -m "docs(readme): update installation instructions"

.gitignore Best Practices

Common Patterns

gitignore# Dependencies
node_modules/
vendor/

# Environment files
.env
.env.local
.env.production

# IDE files
.vscode/
.idea/
*.swp

# OS generated files
.DS_Store
Thumbs.db

# Build artifacts
dist/
build/
*.log

Branch Protection Rules

  • Require pull request reviews

  • Require status checks to pass

  • Require branches to be up to date

  • Restrict pushes to matching branches

  • Require linear history


๐Ÿ”„ DevOps Integration

CI/CD Pipeline Integration

GitHub Actions Example

yamlname: CI/CD Pipeline

on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main ]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    - name: Run tests
      run: npm test

  deploy:
    needs: test
    runs-on: ubuntu-latest
    if: github.ref == 'refs/heads/main'
    steps:
    - uses: actions/checkout@v2
    - name: Deploy to production
      run: ./deploy.sh

Jenkins Pipeline Example

groovypipeline {
    agent any

    stages {
        stage('Checkout') {
            steps {
                git branch: 'main', url: 'https://github.com/user/repo.git'
            }
        }

        stage('Build') {
            steps {
                sh 'npm install'
                sh 'npm run build'
            }
        }

        stage('Test') {
            steps {
                sh 'npm test'
            }
        }

        stage('Deploy') {
            when {
                branch 'main'
            }
            steps {
                sh './deploy.sh'
            }
        }
    }
}

Infrastructure as Code

Terraform with Git

hcl# terraform/main.tf
provider "aws" {
  region = var.aws_region
}

resource "aws_instance" "web" {
  ami           = var.ami_id
  instance_type = var.instance_type

  tags = {
    Name = "web-server"
    Environment = var.environment
  }
}

Version Control for Infrastructure

bash# Infrastructure changes workflow
git checkout -b infrastructure/add-rds-instance
# Make terraform changes
git add terraform/
git commit -m "feat(infra): add RDS instance for user data"
git push origin infrastructure/add-rds-instance
# Create pull request for review

๐Ÿ”ง Troubleshooting Guide

Common Issues and Solutions

Merge Conflicts

bash# When conflicts occur
git status
# Edit conflicted files
git add .
git commit -m "resolve: fix merge conflicts"

Accidentally Committed to Wrong Branch

bash# Move commits to correct branch
git checkout correct-branch
git cherry-pick abc123
git checkout wrong-branch
git reset --hard HEAD~1

Lost Commits

bash# Find lost commits
git reflog
# Recover lost commit
git checkout abc123
git branch recovery-branch

Large File Issues

bash# Remove large file from history
git filter-branch --force --index-filter \
'git rm --cached --ignore-unmatch large-file.zip' \
--prune-empty --tag-name-filter cat -- --all

Recovery Strategies

Backup Before Risky Operations

bash# Create backup branch
git branch backup-$(date +%Y%m%d-%H%M%S)

# Tag important commits
git tag -a v1.0.0 -m "Release version 1.0.0"

๐Ÿ“š Command Reference

Essential Commands

Basic Operations

bash# Initialize repository
git init

# Clone repository
git clone <url>

# Check status
git status

# Add files
git add <file>
git add .

# Commit changes
git commit -m "message"

# Push changes
git push origin <branch>

# Pull changes
git pull origin <branch>

Branching

bash# Create branch
git branch <branch-name>

# Switch branch
git checkout <branch-name>

# Create and switch
git checkout -b <branch-name>

# Delete branch
git branch -d <branch-name>

# Delete remote branch
git push origin --delete <branch-name>

Merging

bash# Merge branch
git merge <branch-name>

# Merge with no fast-forward
git merge --no-ff <branch-name>

# Abort merge
git merge --abort

Advanced Operations

bash# Interactive rebase
git rebase -i HEAD~3

# Stash changes
git stash

# Apply stash
git stash apply

# View history
git log --oneline

# Show differences
git diff

๐ŸŒ Real-World Scenarios

Scenario 1: Team Collaboration

Setup

bash# Developer A creates feature branch
git checkout -b feature/user-profiles
git push -u origin feature/user-profiles

# Developer B works on same feature
git checkout feature/user-profiles
git pull origin feature/user-profiles

Collaboration Workflow

bash# Regular sync with main
git checkout main
git pull origin main
git checkout feature/user-profiles
git rebase main

# Push updates
git push origin feature/user-profiles

Scenario 2: Hotfix Deployment

Emergency Fix Process

bash# Create hotfix from main
git checkout main
git checkout -b hotfix/critical-security-fix

# Make fix
git add .
git commit -m "fix(security): patch SQL injection vulnerability"

# Deploy hotfix
git checkout main
git merge hotfix/critical-security-fix
git push origin main

# Merge back to develop
git checkout develop
git merge hotfix/critical-security-fix
git push origin develop

Scenario 3: Feature Flag Deployment

Gradual Rollout

bash# Feature branch with flag
git checkout -b feature/new-dashboard
# Implement feature with flag
git commit -m "feat(dashboard): add new dashboard behind feature flag"

# Deploy to staging
git checkout staging
git merge feature/new-dashboard
git push origin staging

# Deploy to production
git checkout main
git merge feature/new-dashboard
git push origin main

๐ŸŽฏ Summary

Key Achievements

  • โœ… Mastered Git fundamentals and architecture

  • โœ… Implemented effective branching strategies

  • โœ… Performed advanced Git operations

  • โœ… Applied Git best practices

  • โœ… Integrated Git into DevOps workflows

Skills Developed

  • Repository Management: Creating, cloning, and managing repositories

  • Branching: Feature branches, Git flow, and merge strategies

  • Advanced Operations: Rebase, stash, and history manipulation

  • Collaboration: Team workflows and conflict resolution

  • DevOps Integration: CI/CD pipelines and infrastructure as code

Next Steps

Week 4 will focus on Build and Package Manager Tools, where Git knowledge becomes foundational for:

  • Automated builds triggered by Git events

  • Version tagging and release management

  • Artifact versioning and deployment

  • CI/CD pipeline orchestration


๐Ÿ“– Additional Resources

Official Documentation

Interactive Learning

Books

  • Pro Git by Scott Chacon and Ben Straub

  • Git Pocket Guide by Richard E. Silverman

  • Version Control with Git by Jon Loeliger


This documentation serves as a comprehensive guide for Git mastery in DevOps environments. Regular updates and improvements will be made based on practical experience and community feedback.

Author: DevOps Bootcamp Week 3 Documentation
Last Updated: Week 3 Completion
Next Update: Week 4 - Build and Package Manager Tools Integration


Tags: #Git #DevOps #VersionControl #Documentation #TechWorldWithNana #CI/CD #BestPractices #Tutorial

0
Subscribe to my newsletter

Read articles from Dev Dave directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Dev Dave
Dev Dave