Skip to content
Go back

Version Control with Git

Edit page

Version control is essential for any DevOps engineer. You’ll be writing infrastructure code, automation scripts, and configuration files that need to be tracked, shared, and versioned just like application code.

Core Git Workflow

Understanding the basic Git workflow is crucial:

Working Directory → git add → Staging Area → git commit → Local Repository → git push → Remote Repository

Why the Staging Area?

The staging area acts as a buffer between your working directory and commits. This allows you to:

Essential Commands

# Check status of working directory and staging area
git status

# View commit history
git log
git log --oneline --graph  # Compact view with branch visualization

# Configure Git (do this once)
git config --list
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"

Repository Setup

Connecting Local to Remote

# Add remote repository
git remote add origin git@gitlab.com:username/repository.git

# Push and set upstream tracking
git push --set-upstream origin master

Branching Strategies

Feature vs Trunk-Based Development

Feature-Based (Traditional):

Trunk-Based (Modern DevOps):

Branch Operations

# Switch to existing branch
git checkout branch_name

# Create and switch to new branch
git checkout -b branch_name

# Push new branch to remote
git push --set-upstream origin branch_name

# Delete local branch after merge
git branch -d branch_name

Handling Changes and Conflicts

Pulling Changes

When someone else pushes changes:

# Standard pull (creates merge commit)
git pull

# Rebase pull (cleaner history, no merge commit)
git pull -r

Merge Conflicts

When Git can’t automatically merge changes:

  1. Git marks conflicted files
  2. Manually edit files to resolve conflicts
  3. Stage resolved files: git add conflicted_file
  4. Continue rebase: git rebase --continue
  5. Push changes: git push

Pull/Merge Requests

Essential for code review and collaboration:

Managing Files

.gitignore

Exclude files/directories from version control:

# Create .gitignore file
echo ".idea/" >> .gitignore
echo "*.log" >> .gitignore

# Remove already tracked files
git rm -r --cached .idea
git commit -m "Remove .idea from tracking"

Temporary Storage

# Temporarily store changes
git stash

# Retrieve stashed changes
git stash pop

Viewing History and Navigation

# View commit history with graph
git log --oneline --graph

# Go to specific commit (detached HEAD)
git checkout commit_hash

# Return to latest commit
git checkout branch_name

Undoing Changes

Local Changes (Use Carefully)

# Undo last commit, keep changes in working directory
git reset --soft HEAD~1

# Undo last commit, discard changes completely
git reset --hard HEAD~1

# Modify last commit (add changes or fix message)
git add .
git commit --amend

Remote Changes (When Working Alone)

# Remove commit from remote (dangerous!)
git reset --hard HEAD~1
git push --force

Safe Undoing (Team Environment)

# Create new commit that undoes previous commit
git revert commit_hash

Rule of Thumb: Use reset when working alone, use revert when working in a team.

Branch Merging

# Merge source_branch into current branch
git checkout target_branch
git merge source_branch

Key Takeaways for DevOps

  1. Infrastructure as Code: Your Terraform files, Ansible playbooks, and Kubernetes manifests should live in Git
  2. Automation Scripts: Python scripts, shell scripts, and other automation tools need version control
  3. CI/CD Integration: Build systems need to interact with Git repositories
  4. Collaboration: Even infrastructure changes need code review through pull requests
  5. Rollback Capability: Git history allows you to rollback infrastructure changes safely

Best Practices

Git Commands Cheat Sheet

Git Configuration

CommandDescription
git config --global user.name <name>Define the author name to be used for all commits by the current user
git config --global user.email <email>Define the author email to be used for all commits by the current user
git config --global alias.<alias-name> <git-command>Create shortcut for a Git command. E.g. alias glog “log —graph —oneline”
git config --system core.editor <editor>Set text editor used by commands for all users on the machine
git config --global --editOpen the global configuration file in a text editor for manual editing

Git Basics

CommandDescription
git init <directory>Create empty Git repo in specified directory. Run with no arguments to initialize the current directory as a git repository
git clone <repo>Clone repo located at <repo> onto local machine. Original repo can be located on the local filesystem or on a remote machine via HTTP or SSH
git add <directory>Stage all changes in <directory> for the next commit. Replace <directory> with a <file> to change a specific file
git commit -m "<message>"Commit the staged snapshot, but instead of launching a text editor, use <message> as the commit message
git statusList which files are staged, unstaged, and untracked
git logDisplay the entire commit history using the default format. For customization see additional options
git diffShow unstaged changes between your index and working directory

Git Branches

CommandDescription
git branchList all of the branches in your repo. Add a <branch> argument to create a new branch with the name <branch>
git checkout -b <branch>Create and check out a new branch named <branch>. Drop the -b flag to checkout an existing branch
git merge <branch>Merge <branch> into the current branch

Git Log Options

CommandDescription
git log --limit=<limit>Limit number of commits by <limit>. E.g. “git log -5” will limit to 5 commits
git log --onelineCondense each commit to a single line
git log -pDisplay the full diff of each commit
git log --statInclude which files were altered and the relative number of lines that were added or deleted from each of them
git log --author="<pattern>"Search for commits by a particular author
git log --grep="<pattern>"Search for commits with a commit message that matches <pattern>
git log <since>..<until>Show commits that occur between <since> and <until>. Args can be a commit ID, branch name, HEAD, or any other kind of revision reference
git log -- <file>Only display commits that have the specified file
git log --graph --decorate—graph flag draws a text based graph of commits on left side of commit msgs. —decorate adds names of branches or tags of commits shown

Git Diff

CommandDescription
git diff HEADShow difference between working directory and last commit
git diff --cachedShow difference between staged changes and last commit

Git Reset

CommandDescription
git resetReset staging area to match most recent commit, but leave the working directory unchanged
git reset --hardReset staging area and working directory to match most recent commit and overwrites all changes in the working directory
git reset <commit>Move the current branch tip backward to <commit>, reset the staging area to match, but leave the working directory alone
git reset --hard <commit>Same as previous, but resets both the staging area & working directory to match. Deletes uncommitted changes, and all commits after <commit>

Git Rebase

CommandDescription
git rebase -i <base>Interactively rebase current branch onto <base>. Launches editor to enter commands for how each commit will be transferred to the new base

Git Pull

CommandDescription
git pull --rebase <remote>Fetch the remote’s copy of current branch and rebases it into the local copy. Uses git rebase instead of merge to integrate the branches

Git Push

CommandDescription
git push <remote> --forceForces the git push even if it results in a non-fast-forward merge. Do not use the —force flag unless you’re absolutely sure you know what you’re doing
git push <remote> --allPush all of your local branches to the specified remote
git push <remote> --tagsTags aren’t automatically pushed when you push a branch or use the —all flag. The —tags flag sends all of your local tags to the remote repo

Undoing Changes

CommandDescription
git revert <commit>Create new commit that undoes all of the changes made in <commit>, then apply it to the current branch
git reset <file>Remove <file> from the staging area, but leave the working directory unchanged. This unstages a file without overwriting any changes
git clean -nShows which files would be removed from working directory. Use the -f flag in place of the -n flag to execute the clean

Rewriting Git History

CommandDescription
git commit --amendReplace the last commit with the staged changes and last commit combined. Use with nothing staged to edit the last commit’s message
git rebase <base>Rebase the current branch onto <base>. <base> can be a commit ID, branch name, a tag, or a relative reference to HEAD
git reflogShow a log of changes to the local repository’s HEAD. Add —relative-date flag to show date info or —all to show all refs

Remote Repositories

CommandDescription
git remote add <name> <url>Create a new connection to a remote repo. After adding a remote, you can use <name> as a shortcut for <url> in other commands
git fetch <remote> <branch>Fetches a specific <branch> from the repo. Leave off <branch> to fetch all remote refs
git pull <remote>Fetch the specified remote’s copy of current branch and immediately merge it into the local copy
git push <remote> <branch>Push the branch to <remote>, along with necessary commits and objects. Creates named branch in the remote repo if it doesn’t exist

Edit page
Share this post on:

Previous Post
Artifact Repository Management with Nexus
Next Post
Linux Fundamentals for DevOps