In this lesson you will create a professional GitHub account, secure it with two-factor authentication, and connect your computer to GitHub with SSH keys, so you can push and pull without typing credentials.
📖 What You’ll Learn: creating and completing a GitHub profile, two-factor authentication, HTTPS vs SSH, generating an ed25519 SSH key, the SSH agent on every operating system, adding the key to GitHub, testing the connection and fixing common SSH errors.
👤 Step 1: Create Your GitHub Account
Go to github.com and click Sign up.
Enter your email, a strong password and a username.
Verify your email address with the code GitHub sends you.
Choose the Free plan. It includes unlimited public and private repositories.
💡 Tip: Choose your username carefully: it appears in your profile URL (github.com/your-username) and in every repository link you share with recruiters. Something like asha-verma-qa looks more professional than coolcoder99.
Complete your profile
Add a photo, your name, a short bio (for example “QA Automation Engineer | Playwright | TypeScript”) and your location.
Later, create a profile README by making a public repository with the same name as your username; its README appears on your profile page.
🛡️ Step 2: Turn On Two-Factor Authentication (2FA)
GitHub requires two-factor authentication for accounts that contribute code. Set it up early:
Open Settings, Password and authentication.
Enable 2FA with an authenticator app (Google Authenticator, Microsoft Authenticator, Authy) or a passkey.
Download and store your recovery codes in a safe place. They are the only way back in if you lose your phone.
🔐 HTTPS or SSH? How Git Talks to GitHub
When you push or pull, Git must prove who you are. There are two connection types:
# Windows (Git Bash)
clip < ~/.ssh/id_ed25519.pub
# macOS
pbcopy < ~/.ssh/id_ed25519.pub
# Linux: print it and copy from the terminal
cat ~/.ssh/id_ed25519.pub
On GitHub, open Settings, SSH and GPG keys, New SSH key.
Title: something like “Work laptop”. Key type: Authentication Key. Paste the key and click Add SSH key.
✅ Step 7: Test the Connection
ssh -T git@github.com
The first time, type yes to trust GitHub’s host fingerprint. Success looks like:
Hi asha-verma-qa! You've successfully authenticated, but GitHub does not provide shell access.
Key not added to the agent or GitHub. Run ssh-add -l to list loaded keys and check GitHub Settings, SSH keys
Could not open a connection to your authentication agent
Start the agent: eval "$(ssh-agent -s)" (or Start-Service on Windows)
Connection timed out on port 22
Firewall blocks SSH. Use HTTPS, or SSH over port 443 with host ssh.github.com
Host key verification failed
Remove the old entry with ssh-keygen -R github.com and connect again
📝 Assignment
Create a GitHub account with a professional username and complete your profile.
Enable two-factor authentication and store your recovery codes safely.
Generate an ed25519 SSH key with a passphrase and add it to the SSH agent.
Add the public key to GitHub and confirm with ssh -T git@github.com.
Create an empty public repository called git-practice on GitHub; you will use it in Module 3.
❓ FAQ
🤔 How do I set up an SSH key for GitHub?
Run ssh-keygen -t ed25519 -C "your-email", add the key to the SSH agent with ssh-add, copy the .pub file into GitHub Settings, SSH and GPG keys, then test with ssh -T git@github.com.
🤔 Should I use HTTPS or SSH with GitHub?
Both are secure. HTTPS with Git Credential Manager is easiest for beginners on Windows and macOS. SSH avoids credential prompts and is common on Linux and CI servers.
🤔 Can I use my GitHub password to push code?
No. GitHub requires Git Credential Manager, an SSH key or a personal access token for Git operations.
🤔 Is it safe to share my SSH public key?
Yes. The .pub file is meant to be shared. Never share the private key file without the .pub extension.
🤔 Can I use the same SSH key on several computers?
It is better to create one key per computer. If a laptop is lost, you delete only that key from GitHub.
Before your first commit, Git needs to know who you are and how you like to work. In this lesson you will configure Git once, the right way: identity, editor, default branch, line endings, useful defaults and time-saving aliases.
📖 What You’ll Learn: the system, global and local config levels, setting name and email, choosing an editor, the default branch name, line endings with core.autocrlf, useful extras, aliases, viewing and editing config, and credentials for GitHub.
🪪 Why Configure Git?
Every commit records who made it. Before your first commit, Git needs your name and email. A few more settings make Git friendlier: your favourite editor, the default branch name and how line endings are handled. You set these once per computer.
🧩 The Three Configuration Levels
Level
Option
Applies to
Stored in
System
--system
Every user on the computer
Git’s installation folder
Global
--global
All repositories of your user account
~/.gitconfig
Local
--local (default inside a repo)
One repository only
.git/config in that repo
The most specific level wins: local overrides global, global overrides system. Most of the time you use --global.
💡 Tip: Use the same email as your GitHub account (or GitHub’s private no-reply address, shown in GitHub Settings, Emails). That links your commits to your GitHub profile and contribution graph.
Need a different email for work repositories? Set it locally inside that repository:
cd path/to/work-repo
git config user.email "asha.verma@company.com"
📝 Step 2: Choose Your Editor
Git opens an editor for commit messages, merges and interactive rebases. Set VS Code:
git config --global core.editor "code --wait"
--wait tells Git to wait until you close the editor tab. Other options: "notepad" on Windows, "nano" on Linux and macOS.
🌿 Step 3: Default Branch Name
New repositories should start with main, matching GitHub:
git config --global init.defaultBranch main
↩️ Step 4: Line Endings
Windows and macOS/Linux use different line-ending characters, which can make every line look “changed” in a diff. Configure Git to normalize them:
# Windows
git config --global core.autocrlf true
# macOS and Linux
git config --global core.autocrlf input
For teams, a .gitattributes file in the repository (for example * text=auto) makes this consistent regardless of each person’s settings.
⚙️ Step 5: Useful Extras
git config --global pull.rebase false # git pull merges (default behaviour, avoids a warning)
git config --global push.autoSetupRemote true # first push of a new branch sets its upstream automatically
git config --global color.ui auto # coloured output (usually already on)
git config --global fetch.prune true # remove deleted remote branches on fetch
Now git st runs git status and git lg shows a compact history graph.
🔍 View and Edit Your Configuration
git config --list # all settings
git config --list --show-origin # settings and the file each comes from
git config user.email # one setting
git config --global --edit # open ~/.gitconfig in your editor
git config --global --unset alias.co # remove a setting
Your global file looks like this:
[user]
name = Asha Verma
email = asha.verma@example.com
[core]
editor = code --wait
autocrlf = true
[init]
defaultBranch = main
[alias]
st = status
lg = log --oneline --graph --decorate --all
🔐 Credentials for GitHub over HTTPS
When you push over HTTPS, Git needs to authenticate with GitHub. Git for Windows and recent macOS setups use Git Credential Manager, which opens the browser once and stores the token securely. On Linux you can install Git Credential Manager or use SSH keys instead, covered in the next lesson.
⚠️ Common mistake: GitHub does not accept your account password for Git operations. Use Git Credential Manager, SSH keys or a personal access token.
📝 Assignment
Set your global name, email, editor (VS Code), default branch (main) and line-ending setting.
Run git config --list --show-origin and find which file each of your settings is stored in.
In any repository, set a local email and confirm with git config user.email that it overrides the global one.
Open ~/.gitconfig with git config --global --edit and read through it.
❓ FAQ
🤔 How do I set my username and email in Git?
Run git config --global user.name "Your Name" and git config --global user.email "you@example.com". Check with git config --list.
🤔 How do I change the default branch name to main?
git config --global init.defaultBranch main. New repositories created with git init then start on main.
🤔 Where is the Git config file?
The global file is ~/.gitconfig in your home folder; each repository also has .git/config. Run git config --list --show-origin to see every file in use.
🤔 How do I set VS Code as the Git editor?
git config --global core.editor "code --wait".
🤔 What is core.autocrlf?
It controls line-ending conversion. Use true on Windows and input on macOS and Linux to avoid noisy diffs caused by different line endings.
Before you can use Git, it has to be installed on your computer. This lesson walks you through installing Git on Windows (with the installer or winget) and on the most popular Linux distributions, with the installer options that matter and fixes for common problems.
📖 What You’ll Learn: checking for an existing Git, the Git for Windows installer and its key options, installing with winget, installing on Ubuntu, Fedora, Arch and others, updating Git, and troubleshooting.
✅ Before You Start
Check whether Git is already installed. Open a terminal (Command Prompt, PowerShell or Windows Terminal on Windows; Terminal on Linux) and run:
git --version
If you see something like git version 2.47.1, Git is installed; you can still follow this lesson to update it. If you see “command not found” or “‘git’ is not recognized”, install it now.
⚠️ Common mistake: If git is still “not recognized”, close every terminal and VS Code window and open them again so they pick up the updated PATH. If it still fails, re-run the installer and check the PATH option above.
What did the installer add?
Git Bash: a Linux-style terminal for Windows. Commands in this course such as ls, cat and touch work there. See Essential Terminal Commands for Git.
Git GUI: a simple graphical tool (rarely needed).
Git Credential Manager: stores your GitHub login securely.
⚡ Install Git on Windows with winget
Prefer the command line? Windows 10 and 11 include the winget package manager:
winget install --id Git.Git -e --source winget
Close and reopen the terminal, then run git --version. winget uses the installer defaults, so set the default branch name and editor in the next lesson.
📝 Note: Distribution packages can be a few versions behind the latest Git release. That is fine for this course. On Ubuntu you can get newer versions from the official Git PPA: sudo add-apt-repository ppa:git-core/ppa, then sudo apt update && sudo apt install git.
Reopen the terminal; re-run the installer with the PATH option “from the command line and also from 3rd-party software”
VS Code does not find Git
Restart VS Code; check Settings, git.path
Permission denied on Linux
Use sudo for the install command
Old version on Linux
Use the distribution’s backports or the Git PPA (Ubuntu)
Corporate proxy blocks downloads
Ask IT for the approved installer, or download on another network
📝 Assignment
Install Git on your computer and paste the output of git --version into a notes file.
On Windows, open Git Bash and run pwd, ls and cd ~. What does each command show?
Open VS Code, open any folder, and check that the Source Control panel (Ctrl + Shift + G) no longer says Git is missing.
Write down which line-ending option you chose during installation, and why it matters for teams.
❓ FAQ
🤔 How do I install Git on Windows?
Download Git for Windows from git-scm.com, run the installer (choose VS Code as editor, “main” as the default branch and the recommended PATH option), then check git --version in a new terminal. Or run winget install --id Git.Git -e --source winget.
🤔 How do I install Git on Ubuntu?
Run sudo apt update and sudo apt install git, then verify with git --version.
🤔 How do I check if Git is installed?
Open a terminal and run git --version. If it prints a version number, Git is installed.
🤔 What is Git Bash?
A terminal installed with Git for Windows that supports Linux-style commands such as ls, cat and rm, which makes following Git tutorials easier on Windows.
🤔 Do I need a GitHub account to install Git?
No. Git works without an account. You will create a GitHub account in Lesson 6 to share your repositories online.
Welcome to Lesson 1 of the free Git and GitHub tutorial. Before typing any commands, you will understand what version control is, what Git and GitHub each do, how they differ, and the key words used throughout the course.
📖 What You’ll Learn: the problem version control solves, what Git is, what GitHub adds, Git vs GitHub, key terms (repository, commit, branch, merge, remote, pull request), the basic workflow, and why Git matters for testers.
That is “version control” done by hand: hard to compare, easy to overwrite, and impossible to share safely with a team. Software projects have the same problem on a much bigger scale: hundreds of files, many people editing them at the same time, and the need to know who changed what, when and why.
Version control software solves this. It records every change to your files as a series of snapshots, lets you go back to any earlier version, and lets several people work on the same project without overwriting each other.
🧠 What Is Git?
Git is the world’s most widely used version control system. It is free, open source, and runs on your own computer.
Created in 2005 by Linus Torvalds, the creator of Linux, to manage the Linux kernel’s source code.
Distributed: every developer has a full copy of the project and its complete history, so you can work offline and nothing depends on a single server.
Fast: most operations (commit, branch, view history) happen locally in milliseconds.
Safe: every snapshot is identified by a cryptographic hash, so history cannot be silently corrupted.
With Git you can:
Save snapshots of your project (commits) with a message explaining the change.
See exactly what changed between any two versions.
Work on new features in isolated branches and merge them when ready.
Undo mistakes, even days later.
☁️ What Is GitHub?
GitHub is an online platform that hosts Git repositories and adds tools for working together. It launched in 2008 and has been owned by Microsoft since 2018. It is the largest home of open-source code in the world.
GitHub adds what Git alone does not have:
GitHub feature
What it gives you
Remote repositories
A shared copy of your project in the cloud
Pull requests
Propose, discuss and review changes before merging
Issues and Projects
Track bugs, tasks and plans
GitHub Actions
Automatically build, test and deploy (CI/CD)
GitHub Pages
Host websites for free
Security tools
Dependabot alerts, secret scanning, code scanning
Profiles
Show your work to recruiters and the community
⚖️ Git vs GitHub: The Key Difference
Git
GitHub
What it is
Version control software
A website and service that hosts Git repositories
Where it runs
On your computer
In the cloud (github.com)
Needs internet
No
Yes
Made by
Linus Torvalds and the open-source community
GitHub Inc., owned by Microsoft
Cost
Free and open source
Free plans, plus paid plans for teams and enterprises
Alternatives
Mercurial, SVN (older)
GitLab, Bitbucket, Azure DevOps Repos
💡 Tip: An easy way to remember it: Git is the tool, GitHub is the place where you share what the tool tracks. You can use Git without GitHub, but GitHub is built around Git.
📚 Key Words You Will Meet in This Course
Term
Meaning
Repository (repo)
A project folder tracked by Git, including its full history
Commit
A saved snapshot of your changes, with a message and an author
Branch
An independent line of work, e.g. a new feature
Merge
Combining the changes from one branch into another
Remote
A copy of the repository on a server, such as GitHub
Clone
Downloading a full copy of a remote repository
Push / Pull
Sending your commits to the remote / getting others’ commits
Pull request (PR)
A GitHub request to review and merge a branch
HEAD
A pointer to the commit you are currently on
🔄 How a Typical Workflow Looks
Your computer GitHub
┌──────────────────────────────────────────┐ ┌──────────────┐
│ Working folder → Staging area → Local repo │ push │ Remote repo │
│ (edit) (git add) (git commit)│ ────▶ │ (shared) │
│ │ ◀──── │ │
└──────────────────────────────────────────┘ pull └──────────────┘
You edit files in your working folder.
You choose which changes to save with git add (the staging area).
You save a snapshot with git commit.
You push commits to GitHub so others can see them, and pull their changes.
Each step has its own lesson in Modules 2 and 3.
🧪 Why Testers and QA Engineers Need Git
Automation frameworks, test data and CI pipelines all live in Git repositories.
Reviewing developers’ pull requests helps you test earlier.
Git and GitHub questions appear in almost every QA automation and SDET interview.
📝 Assignment
In your own words, explain the difference between Git and GitHub to a friend in three sentences.
List three problems in your current work (or studies) that version control would solve.
Visit github.com/explore and find one open-source project related to testing. Note its number of stars, contributors and the date of its last commit.
Write down the meaning of: repository, commit, branch, merge, push and pull.
❓ FAQ
🤔 What is Git in simple words?
Git is free software that keeps a complete history of changes to your project’s files, so you can see what changed, go back to earlier versions and work on several changes in parallel.
🤔 What is the difference between Git and GitHub?
Git is version control software that runs on your computer. GitHub is a website that hosts Git repositories online and adds collaboration features such as pull requests, issues and GitHub Actions.
🤔 Is Git free?
Yes. Git is free and open source. GitHub also has a free plan with unlimited public and private repositories.
🤔 Can I use Git without GitHub?
Yes. Git works fully on your own computer. You only need GitHub (or GitLab, Bitbucket) to share repositories and collaborate online.
🤔 Who uses Git?
Almost every software team, from startups to Microsoft and Google, as well as testers, DevOps engineers, data scientists and technical writers.
GitHub Actions relies on Git object mechanics. Workflows are declared as code and committed directly to your repository inside the .github/workflows/ directory. GitHub observes changes to Git references (refs/heads/<branch>, refs/tags/<tag>, refs/pull/<number>/merge) to evaluate trigger rules.
How Git Mechanics Map to Actions
Commits & Pushes: Every git push transmits a SHA hash and branch ref that GitHub Actions uses to check out the exact state of your code.
Pull Requests: A PR trigger creates a virtual merge commit (refs/pull/PR_NUMBER/merge) combining your source branch with the target branch to test collision-free execution.
Tags & Releases: Semantic version tags (v1.0.0) trigger build, package, and publish workflows.
Workflows are written in YAML (YAML Ain’t Markup Language). YAML uses strictly spaces for indentation (tabs are forbidden) and relies on key-value pairs, scalar types, arrays, and dictionaries.
Key Syntax Rules for GitHub Actions
Indentation: standard is 2 spaces per level.
Lists/Sequences: Prefixed with a hyphen and a space (- item).
Multi-line Strings: Use | to preserve line breaks or > to fold line breaks into spaces.
The on key determines when a workflow runs. You can listen to single events, array events, or apply fine-grained activity filters and path filters.
Filtering Rules
branches: Restrict runs to specific target branches.
paths / paths-ignore: Trigger only when specific files change.
tags: Trigger on Git tags matching glob patterns.
YAML
name: Event Trigger Masterclass
on:
# Trigger on pushes to main or release branches, but only if code inside src/ changed
push:
branches:
- main
- 'releases/v*'
paths:
- 'src/**'
- 'package.json'
paths-ignore:
- '**.md'
# Trigger on Pull Requests targeting main branch when opened or synchronized
pull_request:
types: [opened, synchronize, reopened]
branches:
- main
# Trigger on tag creation matching v1.0.0, v2.1.0, etc.
push:
tags:
- 'v*.*.*'
5. Jobs and Steps
Job: A set of steps running on a specific host environment (runs-on). Jobs run in parallel by default.
Step: An individual task executed sequentially inside a job. Steps share a filesystem and environment state on the runner VM.
YAML
name: Job Dependency Pipeline
on: push
jobs:
compile:
runs-on: ubuntu-latest
steps:
- name: Step 1 - Build
run: echo "Compiling assets..."
test:
needs: compile # Forces 'test' to wait until 'compile' finishes successfully
runs-on: ubuntu-latest
steps:
- name: Step 1 - Unit Test
run: echo "Executing unit tests..."
deploy:
needs: [compile, test] # Waits for both upstream jobs
runs-on: ubuntu-latest
steps:
- name: Step 1 - Deploy
run: echo "Deploying to production..."
6. Using Marketplace Actions
Instead of writing raw shell scripts for every task, you can import community and official actions from the GitHub Marketplace using the uses: keyword.
Versioning Actions
@v4 (Major version tag – receives non-breaking updates).
@v4.1.2 (Exact semantic version).
@8f4b7f8... (Full commit SHA – most secure, immutable).
GitHub Actions handles environment configuration at the workflow, job, or step scope. Sensitive credentials must be stored as Encrypted Secrets in repository/organization settings.
Expressions let you evaluate programmatic conditions and access context objects (github, env, runner, steps, secrets). Use if: directives to skip jobs or steps dynamically.
YAML
jobs:
conditional-job:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Execute on main branch only
if: github.ref == 'refs/heads/main'
run: echo "This step runs ONLY on pushes to main."
- name: Execute step with custom status check functions
id: test_step
run: npm test
# Runs ONLY if the previous step failed
- name: Report Failure
if: failure() && steps.test_step.outcome == 'failure'
run: echo "The test execution step failed!"
# Runs ALWAYS, regardless of prior step pass/fail state
- name: Always Cleanup
if: always()
run: echo "Cleaning up temporary test artifacts..."
9. Matrix Strategy
A Matrix Strategy generates multiple job runs by defining input variables across OSs, runtimes, or database versions. GitHub Actions expands these configurations into a parallel execution grid.
YAML
jobs:
matrix-build:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false # Keep running other matrix jobs even if one fails
max-parallel: 4 # Limit concurrent runners
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
node-version: [18, 20]
# Include specific additional configuration
include:
- os: ubuntu-latest
node-version: 22
experimental: true
# Exclude invalid or unwanted combinations
exclude:
- os: windows-latest
node-version: 18
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
- run: node -v
10. Caching Dependencies
To speed up workflow runs, use actions/cache or built-in caching inside setup actions. Caches persist archive files between workflow runs using a unique cache key (typically hashed from lockfiles).
Artifacts allow you to persist output files (build binaries, test reports, coverage HTML) beyond the runner’s ephemeral lifecycle and pass data between independent jobs.
GitHub Actions runners come pre-configured with Docker, enabling step containers, containerized jobs, service containers (databases/queues), and image publishing.
To deploy safely to modern cloud infrastructure, never use long-lived access key secrets. Use OpenID Connect (OIDC) to request temporary, short-lived tokens using IAM Role assumption.
YAML
name: Keyless OIDC AWS Deployment
on:
push:
branches: [ "main" ]
jobs:
deploy-aws:
runs-on: ubuntu-latest
# Required permission to request the OIDC JWT token from GitHub
permissions:
id-token: write
contents: read
steps:
- uses: actions/checkout@v4
- name: Authenticate with AWS via OIDC
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/GitHubActionsDeploymentRole
aws-region: us-east-1
- name: Deploy to S3 Static Bucket
run: |
aws s3 sync ./dist s3://my-production-app-bucket --delete
16. Enterprise CI/CD Patterns and Security
Production enterprise workflows require strict security practices: Zero Trust permissions, Pinned Action Hashes, Concurrency Controls, and Protected Environments.
A matrix strategy lets you run a single job multiple times using variations of inputs (like different OSs, runtime versions, or build flags). GitHub Actions automatically creates a parallel job for every possible combination of matrix variables.
This example runs 6 parallel jobs ($2 \text{ OSs} \times 3 \text{ Node versions}$).
2. Explain Caching
Caching stores dependencies (such as node_modules, Maven packages, or Docker layers) across workflow runs. Because runner VMs are completely wiped after every job, downloading dependencies repeatedly wastes time and bandwidth.
You can use actions/cache@v4 or built-in caching options inside setup actions (like actions/setup-node).
When a cache key matches, the runner downloads the pre-packaged dependencies instead of reinstalling them from the internet.
3. How Do You Upload Artifacts?
Artifacts are files or directories generated during a job (e.g., compiled binaries, test coverage logs, APKs) that you want to save after the runner VM is destroyed.
You use the actions/upload-artifact@v4 action to attach files to the workflow run.
Uploaded artifacts can be downloaded manually from the GitHub UI or programmatically by other jobs.
4. How Do Jobs Communicate?
Because every job executes in a completely isolated virtual machine, they do not share filesystem memory or local variables directly. Jobs communicate in two primary ways:
Method A: Job Outputs (For Small Data / Strings)
Pass scalar values (like commit IDs, version numbers, or status flags) via $GITHUB_OUTPUT.
Pass files between jobs using actions/upload-artifact in Job 1 and actions/download-artifact in Job 2.
5. Explain Reusable Workflows
Reusable Workflows allow you to avoid duplicating workflow code across repositories or within the same repository. Instead of copying and pasting pipeline definitions, you create a central workflow file and invoke it from caller workflows.
A reusable workflow must use the workflow_call trigger:
Executes a pre-packaged Action or Reusable Workflow.
Source
Runs directly on the runner shell (Bash, PowerShell, zsh).
Fetched from GitHub Marketplace, local files, or public repositories.
Example
run: npm test
uses: actions/checkout@v4
7. What is needs?
By default, jobs in a workflow execute in parallel. The needs keyword defines dependency requirements to force sequential execution or form an execution chain (DAG).
YAML
jobs:
test:
runs-on: ubuntu-latest
steps:
- run: npm test
deploy:
needs: test # Waits for 'test' job to complete successfully
runs-on: ubuntu-latest
steps:
- run: ./deploy.sh
If test fails, deploy is automatically skipped.
8. How Do You Trigger Workflows Conditionally?
You can run workflows, jobs, or individual steps conditionally using if expressions or trigger filters:
Method A: Step or Job Level if Condition
YAML
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Deploy to Prod
# Runs only if the event is a push to main branch
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
run: ./deploy-prod.sh
Method B: Event Path/Branch Filtering (on)
YAML
on:
push:
branches:
- main
paths:
- 'src/**' # Triggers only if files in src/ change
9. What are Environments?
Environments describe continuous deployment targets like production, staging, or development. They allow you to attach security controls and configuration variables directly to a deployment target.
Key features of Environments:
Required Reviewers: Pause workflow execution until specified team members manually approve.
Wait Timers: Delay deployment after a trigger (e.g., wait 15 minutes before pushing).
Environment Secrets/Variables: Restrict deployment keys so they are only accessible when running against that specific environment.
Concurrency Groups ensure that only a single job or workflow run within a designated group executes at any given time. If a new run starts while a previous run is in progress, GitHub Actions can automatically cancel the old run or queue the new run.
This prevents deployment race conditions or redundant builds when developers rapidly push multiple commits.
YAML
name: Deploy Pipeline
on: push
# Prevents simultaneous deployments on the same branch
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true # Cancels any previous run still processing
GitHub Actions Advanced Concept
1. What is OIDC Authentication?
OpenID Connect (OIDC) allows GitHub Actions to authenticate directly with cloud providers (AWS, Azure, GCP) using short-lived JWT tokens rather than long-lived, hardcoded credentials or API keys.
The runner requests an OIDC JSON Web Token (JWT) from GitHub’s OIDC provider.
The runner sends this JWT to the cloud provider (e.g., AWS Security Token Service).
The cloud provider validates the signature, evaluates claims (such as repository name, branch, or environment), and exchanges the JWT for short-lived cloud credentials.
2. How Do You Deploy Securely to AWS?
Use OIDC alongside the official aws-actions/configure-aws-credentials action instead of storing AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY inside repository secrets.
Path & Branch Filtering: Use paths and paths-ignore so workflows run only when relevant code changes.
Job Dependencies (needs): Fail fast by placing cheap checks (linting, static analysis) before heavy build/test jobs.
Matrix Filtering / Cancellation: Set fail-fast: true inside matrix strategies so remaining matrix combinations cancel immediately if one fails.
Concurrency Cancellation: Set cancel-in-progress: true inside concurrency blocks to terminate stale builds on new commits.
YAML
on:
push:
paths:
- 'src/**' # Ignore documentation or root README changes
4. How Do You Reuse Workflows Across Repositories?
Reference a reusable workflow stored in an external repository using the {owner}/{repo}/.github/workflows/{filename}.yml@{ref} syntax. The target repository must have its visibility set to public or shared within an organization.
YAML
# In repo: caller-org/app-repo
jobs:
call-shared-ci:
# References shared pipeline from security-team/shared-workflows repo
uses: security-team/shared-workflows/.github/workflows/ci-template.yml@v2.1
with:
environment: 'staging'
secrets: inherit # Automatically passes caller secrets to called workflow
5. What are Composite Actions?
A Composite Action aggregates multiple step commands or actions into a single reusable action. Unlike reusable workflows (which encompass full jobs), composite actions run as a single step within a job.
They are defined in an action.yml file and require runs.using: 'composite' and an explicit shell: directive on every run step.
YAML
# .github/actions/setup-node-and-cache/action.yml
name: 'Setup Node and Cache'
description: 'Custom setup wrapper for project standard initialization'
inputs:
node-version:
default: '20'
runs:
using: 'composite'
steps:
- uses: actions/setup-node@v4
with:
node-version: ${{ inputs.node-version }}
cache: 'npm'
- name: Install dependencies
shell: bash # Required in composite actions
run: npm ci
6. How Do You Secure Secrets?
Use Least Privilege: Restrict secret exposure using Environment Secrets gated behind approval environments.
Never Print Secrets: Avoid passing secrets directly into shell scripts where set -x or debug flags could print them to standard output.
Avoid PR Triggers from Forks: Workflows triggered by pull_request from fork repositories do not receive access to repository secrets by default.
Pass Secrets via Environment Variables: Pass secrets to scripts using env blocks rather than raw string replacement inside commands to avoid process listing injection.
YAML
steps:
- name: Run Secure Script
env:
DB_PASSWORD: ${{ secrets.DB_PASSWORD }} # Passed as env var, not inline text
run: python db_migrate.py
7. What is Least-Privilege Workflow Permission?
By default, GITHUB_TOKEN may inherit read/write permissions depending on organization settings. To enforce least privilege, set global workflow permissions to read-all or contents: read, and grant specific elevated scopes only to the jobs that require them.
YAML
name: Security Standard Pipeline
on: push
# Deny all permissions globally by default
permissions: {}
jobs:
build_and_test:
runs-on: ubuntu-latest
permissions:
contents: read # Read-only access to code
steps:
- uses: actions/checkout@v4
- run: npm test
publish_release:
needs: build_and_test
runs-on: ubuntu-latest
permissions:
contents: write # Granted write access ONLY for release generation
steps:
- uses: actions/checkout@v4
- run: gh release create v1.0.0
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
8. How Do You Handle Rollbacks?
Automate rollbacks using conditional steps (if: failure()) or a dedicated rollback workflow triggered by deployment checks.
Deploy the new application version to an isolated “Green” environment, perform health checks, and swap live traffic routing (e.g., DNS, Load Balancer, or ingress route) from “Blue” to “Green”.
YAML
jobs:
blue_green_deploy:
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/checkout@v4
- name: Deploy to Green Environment
run: ./deploy-green.sh --version ${{ github.sha }}
- name: Run Integration Tests Against Green
run: ./test-target.sh --url https://green.internal.myapp.com
- name: Switch Traffic (Blue -> Green)
run: ./switch-load-balancer.sh --target green
10. How Do You Debug Failed Workflows?
Enable Runner Diagnostic / Step Debug Logging: Set repository secrets ACTIONS_STEP_DEBUG = true and ACTIONS_RUNNER_DEBUG = true to produce verbose log outputs.
Re-run Jobs with Debug Logging Enabled: Click Re-run jobs -> check Enable debug logging from the GitHub UI interface.
Inspect Artifacts: Save log files, crash dumps, or screenshots using actions/upload-artifact@v4 inside an if: always() step.
YAML
steps:
– name: Run Test Suite
run: npm test
– name: Capture Failure Logs
if: failure()
uses: actions/upload-artifact@v4
with:
name: test-failure-logs
path: ./logs/
GitHub Actions is an automated CI/CD (Continuous Integration and Continuous Delivery) platform built directly into GitHub. It allows you to automate software workflows directly from your repository—such as building code, running tests, publishing packages, or deploying applications—whenever specific GitHub events occur.
YAML
# Simple example: Running tests whenever code is pushed
name: CI Pipeline
on: [push]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm install
- run: npm test
2. What is a Workflow?
A Workflow is an automated, configurable process defined in a .yml (or .yaml) file stored inside your repository’s .github/workflows/ directory. A repository can have multiple workflows (e.g., one for unit testing, one for code linting, and one for production deployments).
Workflows are triggered by events (like a push, pull_request, or schedule) and consist of one or more jobs.
YAML
# .github/workflows/greeting.yml
name: Daily Greeting
on:
schedule:
- cron: '0 9 * * 1-5' # Runs every weekday at 9 AM UTC
jobs:
greet:
runs-on: ubuntu-latest
steps:
- run: echo "Good morning, team!"
3. What is a Runner?
A Runner is an application or server that executes the jobs inside a GitHub Actions workflow. When a workflow is triggered, GitHub assigns a runner to listen for available jobs, run the steps, and stream the logs and results back to GitHub.
Runners come pre-installed with standard development tooling (Git, Node.js, Python, Docker, Docker Compose, CLI tools, etc.).
4. Difference Between Job and Step
Job: A group of steps that execute on the same runner instance. By default, if a workflow has multiple jobs, they run in parallel unless configured to run sequentially using needs.
Step: An individual task within a job. Steps run sequentially on the runner and share the same environment and filesystem. A step can either run a shell command (run) or execute a reusable action (uses).
Feature
Job
Step
Execution
Runs in parallel (default) or sequentially
Always runs sequentially inside its parent job
Environment
Runs on its own separate virtual machine / runner
Shares the virtual machine environment with other steps in the job
Data Sharing
Filesystem is isolated from other jobs
Shares local filesystem changes directly with subsequent steps
YAML (“YAML Ain’t Markup Language”) is a human-readable data format used for configuration files. GitHub Actions uses YAML to structure workflows. It relies strictly on indentation (spaces, never tabs) and key-value pairs to establish hierarchy.
GitHub-hosted runners are fully managed virtual machines hosted by GitHub. Every time a job runs, GitHub spins up a fresh, ephemeral VM running your choice of operating system (Ubuntu Linux, Windows, or macOS), runs the job, and destroys the VM afterward.
Pros: Zero maintenance, completely clean environment per run, automatically updated software packages.
Syntax:runs-on: ubuntu-latest, runs-on: windows-latest, or runs-on: macos-latest.
Self-hosted runners are machines (physical servers, local VMs, cloud instances on AWS/Azure, or Docker containers) that you set up and manage yourself, then register with GitHub.
Pros: Access to private internal networks/databases, custom hardware requirements (e.g., GPUs for AI/ML training), faster builds through persistent caching.
Cons: You are responsible for OS updates, security, and scaling.
GitHub Secrets are encrypted environment variables stored securely in repository, organization, or environment settings. They allow you to store sensitive credentials (e.g., API keys, database passwords, deployment tokens) without hardcoding them into your source code.
GitHub automatically masks secrets in workflow logs (replacing secret values with ***).
workflow_dispatch is an event trigger that allows you to run a workflow manually. Once added to on:, a “Run workflow” button appears in the GitHub Actions tab UI. It can also accept custom input parameters (text, drop-downs, booleans).
actions/checkout is an official, reusable action (actions/checkout@v4) provided by GitHub.
When a job starts, the runner’s workspace is completely empty. actions/checkout clones your repository’s code into the workspace so that subsequent steps (like linter checks, test runs, or build tools) can access and execute against your project files.
YAML
jobs:
build:
runs-on: ubuntu-latest
steps:
# Without checkout, npm build will fail because package.json is missing
- name: Download repository code
uses: actions/checkout@v4
- name: Build project
run: npm run build