InterviewTreedInterviewTreed

InterviewTreed Question Bank

Git, GitHub & CI/CD Interview Questions and Answers

Prepare for Git version control, GitHub collaboration, branching strategies, pull requests, automated testing, CI/CD pipelines, and modern software delivery practices.

Total Questions

80

Beginner

30

Intermediate

32

Advanced

18

Beginner Questions

Foundational concepts, terminology, and core ideas.

Q1Version Control

What is version control?

Version control records changes to files over time so a team can inspect history, compare revisions, restore earlier states, and collaborate safe…

Answer

Version control records changes to files over time so a team can inspect history, compare revisions, restore earlier states, and collaborate safely. Git is a distributed version-control system: each clone contains repository history, not just a working copy.

Syntax

git init
git status
git log --oneline

Example

Track a small application and review who changed a function before a release.

Code example

git init
git add .
git commit -m "Initial version"
git log --oneline

Diagram

Working tree → Staging area → Local repository → Remote repository

Key Points

  • History
  • collaboration
  • rollback
  • traceability
Q2Git Fundamentals

What is Git, and how is it different from GitHub?

Git is the version-control tool that runs locally and manages commits and branches. GitHub is a hosted collaboration platform built around Git re…

Answer

Git is the version-control tool that runs locally and manages commits and branches. GitHub is a hosted collaboration platform built around Git repositories, adding pull requests, reviews, issues, permissions, and automation.

Syntax

git --version
git remote -v

Example

A developer commits with Git locally, then pushes to GitHub so teammates can review the work.

Code example

git add src/app.ts
git commit -m "Add app entry point"
git push origin main

Diagram

Developer + Git locally → GitHub remote → Pull request and review

Key Points

  • Git is the tool
  • GitHub is a hosting/collaboration service
Q3Git Fundamentals

What is a repository?

A repository contains project files and Git metadata, including commit history, branches, tags, and configuration. A working repository may be lo…

Answer

A repository contains project files and Git metadata, including commit history, branches, tags, and configuration. A working repository may be local, hosted remotely, or both.

Syntax

git init
# or
git clone <repository-url>

Example

Clone a team repository before implementing a feature.

Code example

git clone https://github.com/example/team-app.git
cd team-app
git status

Diagram

Remote repository → Clone → Local working repository

Key Points

  • Files plus history
  • local and remote copies
Q4Git Fundamentals

What is the working tree, index, and repository?

The working tree is the checked-out files you edit. The index (staging area) records the exact content planned for the next commit. The repositor…

Answer

The working tree is the checked-out files you edit. The index (staging area) records the exact content planned for the next commit. The repository stores committed objects and history.

Syntax

git status
git add <path>
git commit -m "message"

Example

Stage only the validated API file while leaving a debug experiment unstaged.

Code example

git add src/api.ts
git diff --cached
git commit -m "Validate API input"

Diagram

Working tree → Index → Commit history

Key Points

  • Stage deliberately
  • inspect staged diff before committing
Q5Git Fundamentals

What is a commit?

A commit is a snapshot of tracked project content plus metadata such as author, timestamp, message, and parent commit references. Commits form th…

Answer

A commit is a snapshot of tracked project content plus metadata such as author, timestamp, message, and parent commit references. Commits form the history graph.

Syntax

git commit -m "Describe change"

Example

Create a commit after tests pass for a focused bug fix.

Code example

git add src/checkout.ts
git commit -m "Fix discount rounding"

Diagram

Commit B → parent Commit A → earlier history

Key Points

  • Small, coherent, meaningful commits
Q6Git Fundamentals

How do you initialize and clone repositories?

Use `git init` to start tracking a directory, or `git clone` to create a local copy of an existing remote repository with its history and remote…

Answer

Use `git init` to start tracking a directory, or `git clone` to create a local copy of an existing remote repository with its history and remote configuration.

Syntax

git init
 git clone <url>

Example

Start a new library locally or join an existing project by cloning it.

Code example

mkdir demo && cd demo
git init
# existing project:
git clone https://github.com/example/demo.git

Diagram

New folder → git init; Existing remote → git clone

Key Points

  • Choose init for new repository
  • clone for existing repository
Q7Daily Git Commands

How do you check repository status?

`git status` reports the current branch, staged changes, unstaged changes, and untracked files. It is a safe first command before staging, commit…

Answer

`git status` reports the current branch, staged changes, unstaged changes, and untracked files. It is a safe first command before staging, committing, or switching branches.

Syntax

git status
git status --short

Example

Check whether a generated file is untracked before committing.

Code example

git status --short
# M src/app.ts
# ?? notes.txt

Diagram

Files → status classification → next action

Key Points

  • Use frequently
  • short format is compact
Q8Daily Git Commands

How do you stage and unstage files?

`git add` stages content for the next commit. To unstage without discarding edits, use `git restore --staged <path>`. Staging is content-based, s…

Answer

`git add` stages content for the next commit. To unstage without discarding edits, use `git restore --staged <path>`. Staging is content-based, so review the staged diff.

Syntax

git add <path>
git restore --staged <path>

Example

Stage only source changes, then unstage a mistakenly added local config file.

Code example

git add src/
git restore --staged .env.local
git diff --cached

Diagram

Edited file → git add → staged snapshot

Key Points

  • Unstaging preserves working-tree edits
Q9Daily Git Commands

How do you commit changes?

A commit records staged content. Use an imperative, specific message that explains the change. Avoid committing secrets, temporary files, or unre…

Answer

A commit records staged content. Use an imperative, specific message that explains the change. Avoid committing secrets, temporary files, or unrelated changes.

Syntax

git commit -m "Add retry policy"

Example

Commit a tested retry policy separately from a documentation update.

Code example

git add src/retry.ts
git diff --cached
git commit -m "Add retry policy"

Diagram

Review diff → Commit → History

Key Points

  • Commit only reviewed staged content
Q10Daily Git Commands

How do you inspect changes with diff?

`git diff` shows unstaged changes; `git diff --staged` (or `--cached`) shows staged changes. Comparing commits or branches helps review scope bef…

Answer

`git diff` shows unstaged changes; `git diff --staged` (or `--cached`) shows staged changes. Comparing commits or branches helps review scope before integration.

Syntax

git diff
git diff --staged
git diff main...feature/login

Example

Review the exact code that will enter a pull request.

Code example

git diff -- src/auth.ts
git diff --staged

Diagram

Working changes → Diff review → Commit/PR

Key Points

  • Diff is a core review and debugging tool
Q11Daily Git Commands

How do you inspect commit history?

`git log` displays commit history and supports compact, graph, author, and date views. Use `git show <commit>` to inspect a commit's metadata and…

Answer

`git log` displays commit history and supports compact, graph, author, and date views. Use `git show <commit>` to inspect a commit's metadata and patch.

Syntax

git log --oneline --graph --decorate --all
git show <commit>

Example

Trace when a configuration default changed and inspect the associated patch.

Code example

git log --oneline -- src/config.ts
git show a1b2c3d

Diagram

Commit graph with parent links

Key Points

  • History can be filtered by file, author, or range
Q12Repository Hygiene

What is a .gitignore file?

`.gitignore` lists untracked paths Git should normally ignore, such as build output, local secrets, caches, and editor files. It does not stop tr…

Answer

`.gitignore` lists untracked paths Git should normally ignore, such as build output, local secrets, caches, and editor files. It does not stop tracking a file already committed.

Syntax

node_modules/
dist/
.env.local

Example

Prevent local build output and environment-specific settings from appearing as untracked files.

Code example

printf "node_modules/\ndist/\n.env.local\n" >> .gitignore
git status

Diagram

Generated/local files → .gitignore → not shown as untracked

Key Points

  • Never commit secrets
  • untrack existing files separately
Q13Remote Repositories

What is a remote in Git?

A remote is a named reference to another repository, commonly hosted on GitHub. `origin` is a conventional default name, not a special Git keywor…

Answer

A remote is a named reference to another repository, commonly hosted on GitHub. `origin` is a conventional default name, not a special Git keyword.

Syntax

git remote -v
git remote add origin <url>

Example

Connect a local repository to the team's GitHub repository.

Code example

git remote add origin https://github.com/example/app.git
git push -u origin main

Diagram

Local repo ⇄ named remote origin

Key Points

  • A repository can have multiple remotes
Q14Remote Repositories

What is the difference between fetch and pull?

`git fetch` downloads remote objects and updates remote-tracking references without changing the current branch. `git pull` fetches and then inte…

Answer

`git fetch` downloads remote objects and updates remote-tracking references without changing the current branch. `git pull` fetches and then integrates the configured upstream, usually by merge or rebase.

Syntax

git fetch origin
git pull --rebase origin main

Example

Fetch first to inspect incoming commits before deciding how to integrate them.

Code example

git fetch origin
git log --oneline HEAD..origin/main
git merge origin/main

Diagram

Remote → fetch → remote-tracking branch → merge/rebase

Key Points

  • Fetch is inspectable
  • pull also integrates
Q15Remote Repositories

How do you push a branch to GitHub?

`git push` sends local commits to a remote branch. For a new branch, `-u` sets its upstream so later push and pull commands can omit remote and b…

Answer

`git push` sends local commits to a remote branch. For a new branch, `-u` sets its upstream so later push and pull commands can omit remote and branch names.

Syntax

git push -u origin feature/search

Example

Publish a new feature branch so a teammate can review it.

Code example

git switch -c feature/search
git add .
git commit -m "Add search filter"
git push -u origin feature/search

Diagram

Local feature branch → push → GitHub branch

Key Points

  • Push commits, not uncommitted working-tree changes
Q16Branching

What is a branch?

A branch is a movable reference to a commit. Branches let developers work on features or fixes independently without changing the branch used for…

Answer

A branch is a movable reference to a commit. Branches let developers work on features or fixes independently without changing the branch used for production releases.

Syntax

git branch
git switch -c feature/profile

Example

Develop a profile page on a separate branch while `main` remains stable.

Code example

git switch -c feature/profile
# edit files
git add . && git commit -m "Add profile page"

Diagram

main: A—B—C; feature: A—B—D

Key Points

  • Branches are lightweight references
Q17Branching

How do you create, switch, and delete branches?

Use `git branch` to list or create branches and `git switch` to move between them. Delete a merged local branch with `-d`; `-D` force-deletes and…

Answer

Use `git branch` to list or create branches and `git switch` to move between them. Delete a merged local branch with `-d`; `-D` force-deletes and should be used carefully.

Syntax

git switch -c feature/cart
git switch main
git branch -d feature/cart

Example

Create a short-lived branch, merge it, then remove the local reference.

Code example

git switch -c fix/cart-total
# after merge
git switch main
git branch -d fix/cart-total

Diagram

main ↔ feature branch

Key Points

  • Prefer `-d`
  • force deletion can discard unmerged work
Q19Branch Integration

Explain Git merge.

Merge integrates histories by creating a merge commit when needed, or by fast-forwarding when the target can move directly forward. Conflicts occ…

Answer

Merge integrates histories by creating a merge commit when needed, or by fast-forwarding when the target can move directly forward. Conflicts occur when Git cannot automatically combine changes.

Syntax

git switch main
git merge feature/cart

Example

Merge a reviewed feature branch into the current integration branch.

Code example

git switch main
git pull origin main
git merge --no-ff feature/cart

Diagram

main A—B—M; feature A—B—C; M joins both

Key Points

  • Merge preserves branch topology
  • conflict resolution may be required
Q22Conflict Resolution

What is a merge conflict, and how do you resolve it?

A conflict means Git cannot determine the intended combined content. Inspect conflict markers, understand both changes, edit the file to the corr…

Answer

A conflict means Git cannot determine the intended combined content. Inspect conflict markers, understand both changes, edit the file to the correct result, run tests, stage the resolution, and continue the merge or rebase.

Syntax

<<<<<<< HEAD
ours
=======
theirs
>>>>>>> feature

Example

Two branches change the same validation rule; agree on the intended behavior rather than blindly choosing one side.

Code example

git status
# edit conflicted file
# remove conflict markers and keep correct code
git add src/validation.ts
git commit

Diagram

Ours + theirs → manual decision → tests → resolved commit

Key Points

  • Do not leave conflict markers
  • validate behavior after resolution
Q26Daily Git Commands

What is `git stash`?

Stash temporarily saves working-tree and optionally staged changes so you can switch context without committing incomplete work. Stashes are loca…

Answer

Stash temporarily saves working-tree and optionally staged changes so you can switch context without committing incomplete work. Stashes are local and should not be treated as durable backup.

Syntax

git stash push -m "WIP search"
git stash list
git stash pop

Example

Pause an unfinished change to review an urgent hotfix.

Code example

git stash push -u -m "WIP search UI"
git switch main
# later
git switch feature/search
git stash pop

Diagram

Dirty working tree → stash → clean tree → restore

Key Points

  • Use `-u` for untracked files
  • inspect conflicts after pop
Q30Releases & Tags

What are tags, and how are they used for releases?

Tags name specific commits, commonly release versions. Annotated tags store metadata and are preferred for releases. Pushing a branch does not ne…

Answer

Tags name specific commits, commonly release versions. Annotated tags store metadata and are preferred for releases. Pushing a branch does not necessarily push tags.

Syntax

git tag -a v2.1.0 -m "Release 2.1.0"
git push origin v2.1.0

Example

Tag the exact commit approved for a production release.

Code example

git switch main
git pull --ff-only origin main
git tag -a v2.1.0 -m "Release 2.1.0"
git push origin v2.1.0

Diagram

Release version → tag → immutable commit reference

Key Points

  • Use consistent versioning and release notes
Q31Releases & Tags

What is semantic versioning?

Semantic Versioning expresses a version as MAJOR.MINOR.PATCH: major for incompatible public API changes, minor for backward-compatible functional…

Answer

Semantic Versioning expresses a version as MAJOR.MINOR.PATCH: major for incompatible public API changes, minor for backward-compatible functionality, and patch for backward-compatible fixes, subject to the project's policy.

Syntax

MAJOR.MINOR.PATCH
2.4.1 → 3.0.0 for breaking API change

Example

Release a compatible bug fix as a patch version.

Code example

# Example release labels:
v2.4.0  # new compatible feature
v2.4.1  # compatible bug fix
v3.0.0  # breaking change

Diagram

2.4.1 → patch; 2.5.0 → minor; 3.0.0 → major

Key Points

  • Pre-1.0 projects may use different conventions
Q32Pull Requests

What are GitHub pull requests?

A pull request (PR) proposes changes from a source branch into a target branch. It provides a review discussion, diff, automated checks, approval…

Answer

A pull request (PR) proposes changes from a source branch into a target branch. It provides a review discussion, diff, automated checks, approvals, and an auditable integration point.

Syntax

Source branch → Open pull request → Review/checks → Merge

Example

Open a PR from `feature/search` into `main` after pushing the branch.

Code example

git push -u origin feature/search
# Then create the PR in GitHub UI or CLI
gh pr create --base main --head feature/search --title "Add search" --body "Adds search filtering."

Diagram

Feature branch → PR → checks/review → main

Key Points

  • Keep PRs focused
  • explain why and how to test
Q33Pull Requests

What should a good pull request description include?

A good PR describes the problem, the solution, user-visible impact, testing performed, risks, screenshots when relevant, and linked issue. It sho…

Answer

A good PR describes the problem, the solution, user-visible impact, testing performed, risks, screenshots when relevant, and linked issue. It should make reviewer context easy to understand.

Syntax

## Summary
## Changes
## Testing
## Risks

Example

A PR for a pagination fix includes reproduction steps and the regression test.

Code example

gh pr create --title "Fix pagination boundary" --body "## Summary
Fixes last-page calculation.

## Testing
- Unit tests
- Manual boundary check"

Diagram

Problem → implementation → evidence → reviewer decision

Key Points

  • Describe behavior, not just file changes
Q37GitHub Actions

What is GitHub Actions?

GitHub Actions is GitHub's automation platform. Workflow YAML files define events, jobs, runners, steps, and optional reusable actions to automat…

Answer

GitHub Actions is GitHub's automation platform. Workflow YAML files define events, jobs, runners, steps, and optional reusable actions to automate builds, tests, security checks, and deployment.

Syntax

# .github/workflows/ci.yml
name: CI
on: [push, pull_request]

Example

Run the test suite automatically for every pull request.

Code example

name: CI
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm ci
      - run: npm test

Diagram

Push/PR event → workflow → runner → steps → status

Key Points

  • Pin and review third-party actions
  • keep workflows least-privileged
Q38CI/CD Fundamentals

What is a CI/CD pipeline?

A pipeline automates repeatable steps from source change through validation and delivery. Continuous integration validates each change; continuou…

Answer

A pipeline automates repeatable steps from source change through validation and delivery. Continuous integration validates each change; continuous delivery keeps releases deployable; continuous deployment automatically releases qualifying changes to production.

Syntax

checkout → install → lint → test → build → package → deploy

Example

A pull request runs tests and build; after merge, a release workflow deploys to staging.

Code example

jobs: validate → build → publish-artifact → deploy-staging

Diagram

Commit → CI validation → artifact → environment deployment

Key Points

  • Separate validation from deployment and protect production
Q41GitHub Actions

How do you trigger a workflow on push and pull request?

Use the `on` key to declare event triggers and branch filters. Keep required PR checks available for the branches protected by repository rules.

Answer

Use the `on` key to declare event triggers and branch filters. Keep required PR checks available for the branches protected by repository rules.

Syntax

on:
  push:
    branches: [main]
  pull_request:

Example

Run validation for pull requests and for pushes to main.

Code example

name: CI
on:
  push:
    branches: [main]
  pull_request:
    branches: [main]
jobs:
  validate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: echo "Validate code"

Diagram

push/PR event → branch filter → job

Key Points

  • Avoid accidentally skipping required checks on target branches
Q47Automated Testing

How do you add automated tests to a pipeline?

Run tests as an explicit pipeline gate and return a failing exit code when a test fails. Include fast unit tests on each PR, and run slower integ…

Answer

Run tests as an explicit pipeline gate and return a failing exit code when a test fails. Include fast unit tests on each PR, and run slower integration or end-to-end tests at suitable stages.

Syntax

npm ci && npm test

Example

Prevent a pull request from merging when unit tests fail.

Code example

- run: npm ci
- run: npm test

Diagram

Commit → tests → pass allows progress; fail blocks pipeline

Key Points

  • Tests must be deterministic and meaningful
Q49Automated Testing

What are linting, formatting, and static analysis?

Linting flags suspicious patterns and style issues; formatting applies consistent layout; static analysis checks code properties without executin…

Answer

Linting flags suspicious patterns and style issues; formatting applies consistent layout; static analysis checks code properties without executing the application. They catch issues early and should run consistently in local development and CI.

Syntax

npm run lint
npm run format:check
npm run typecheck

Example

Fail the PR if TypeScript type checking or linting reports errors.

Code example

- run: npm ci
- run: npm run lint
- run: npm run typecheck

Diagram

Source → lint/format/type checks → test/build

Key Points

  • Keep local and CI tool versions aligned
Q55Deployment Strategies

What is a deployment environment?

An environment represents a target such as development, test, staging, or production and may define secrets, reviewers, branch restrictions, and…

Answer

An environment represents a target such as development, test, staging, or production and may define secrets, reviewers, branch restrictions, and deployment history. Promotion should be controlled by environment risk.

Syntax

dev → staging → production

Example

Require a reviewer before a workflow can deploy to production.

Code example

jobs:
  deploy-prod:
    environment: production
    runs-on: ubuntu-latest
    steps:
      - run: ./deploy.sh production

Diagram

Validated artifact → staging → approval → production

Key Points

  • Separate environment permissions and secrets

Intermediate Questions

Implementation details, practical patterns, and common workflows.

Q18Branching

What is a detached HEAD?

Detached HEAD means `HEAD` points directly to a commit rather than a branch name. It is useful for inspecting old revisions, but new commits can…

Answer

Detached HEAD means `HEAD` points directly to a commit rather than a branch name. It is useful for inspecting old revisions, but new commits can become hard to find unless a branch is created.

Syntax

git switch --detach <commit>
git switch -c investigate-old-bug

Example

Inspect an old release and create a branch if you need to keep a fix.

Code example

git switch --detach v1.4.0
# if editing and committing:
git switch -c hotfix/investigation

Diagram

HEAD → commit (not branch)

Key Points

  • Create a branch to preserve new commits
Q20Branch Integration

What is a fast-forward merge?

A fast-forward occurs when the target branch is an ancestor of the source branch, so Git can move the target reference forward without creating a…

Answer

A fast-forward occurs when the target branch is an ancestor of the source branch, so Git can move the target reference forward without creating a merge commit.

Syntax

git merge --ff-only feature/docs

Example

Use `--ff-only` when policy requires avoiding accidental merge commits.

Code example

git switch main
git merge --ff-only origin/main

Diagram

main A—B; feature A—B—C → main moves to C

Key Points

  • No divergence
  • no merge commit
Q21Branch Integration

What is a three-way merge?

When branches diverge, Git uses their common ancestor and both branch tips to calculate a merge result. Conflicting edits to the same region may…

Answer

When branches diverge, Git uses their common ancestor and both branch tips to calculate a merge result. Conflicting edits to the same region may require manual resolution.

Syntax

git merge feature/payment

Example

Integrate independent work on the main branch and payment branch.

Code example

git switch main
git merge feature/payment
# resolve conflicts, then:
git add src/payment.ts
git commit

Diagram

Base + ours + theirs → merge result

Key Points

  • The merge base is central to conflict analysis
Q23Branch Integration

What is Git rebase?

Rebase replays commits onto a new base, producing a more linear history. Replayed commits have new IDs. Rebase local unpublished work freely, but…

Answer

Rebase replays commits onto a new base, producing a more linear history. Replayed commits have new IDs. Rebase local unpublished work freely, but coordinate before rewriting commits others rely on.

Syntax

git switch feature/cart
git rebase main

Example

Update a feature branch with current main before opening or refreshing a pull request.

Code example

git fetch origin
git switch feature/cart
git rebase origin/main

Diagram

Feature commits replayed on latest main

Key Points

  • Rebase changes commit identity
  • conflicts may recur per commit
Q24Branch Integration

Merge vs rebase: when should you use each?

Merge preserves the actual integration topology and is suitable for shared history. Rebase creates a linear sequence and is useful for cleaning u…

Answer

Merge preserves the actual integration topology and is suitable for shared history. Rebase creates a linear sequence and is useful for cleaning up private work. Avoid rewriting shared/public history unless the team explicitly coordinates it.

Syntax

git merge main
git rebase main

Example

Rebase a private feature branch before review; merge the reviewed change according to repository policy.

Code example

git fetch origin
git rebase origin/main
# resolve, test, then push if allowed

Diagram

Merge: join histories; Rebase: replay commits

Key Points

  • Choose based on collaboration and project policy
Q25Branch Integration

What is cherry-pick?

`git cherry-pick` applies the changes introduced by selected commit(s) onto the current branch, creating new commit IDs. It is useful for targete…

Answer

`git cherry-pick` applies the changes introduced by selected commit(s) onto the current branch, creating new commit IDs. It is useful for targeted fixes but can duplicate changes across branches.

Syntax

git cherry-pick <commit>

Example

Backport a one-line production fix to a maintained release branch.

Code example

git switch release/1.x
git cherry-pick a1b2c3d

Diagram

Commit from branch A → apply patch on branch B

Key Points

  • Resolve conflicts
  • document backports
  • avoid unnecessary duplication
Q27Undo & Recovery

How do you undo the last commit safely?

The right command depends on whether the commit is shared and whether you want to keep its changes. `git revert` creates a new inverse commit; `g…

Answer

The right command depends on whether the commit is shared and whether you want to keep its changes. `git revert` creates a new inverse commit; `git reset` moves the current branch reference and may rewrite local history.

Syntax

git revert <commit>
git reset --soft HEAD~1

Example

Undo a pushed change using revert so teammates' history remains intact.

Code example

git revert a1b2c3d
# for a private local commit only:
git reset --soft HEAD~1

Diagram

Bad commit → inverse commit (shared history)

Key Points

  • Prefer revert for published commits
Q28Undo & Recovery

What is the difference between reset, revert, and restore?

`reset` moves the current branch/HEAD and can alter the index or working tree; `revert` records a new commit that reverses an earlier commit; `re…

Answer

`reset` moves the current branch/HEAD and can alter the index or working tree; `revert` records a new commit that reverses an earlier commit; `restore` replaces file content in the working tree or index.

Syntax

git reset --soft HEAD~1
git revert <commit>
git restore <path>

Example

Choose the command based on whether history is shared and which state you want to change.

Code example

git restore --staged src/app.ts
git restore --source=HEAD -- src/app.ts

Diagram

Reset: move pointer; Revert: add inverse commit; Restore: restore file state

Key Points

  • Understand destructive effects before running reset/restore
Q34Pull Requests

How should code review be performed?

Review correctness, design, readability, security, performance, tests, and maintainability. Ask specific, respectful questions and distinguish bl…

Answer

Review correctness, design, readability, security, performance, tests, and maintainability. Ask specific, respectful questions and distinguish blockers from suggestions. Authors should respond to each thread and keep the diff reviewable.

Syntax

Review checklist: correctness → tests → security → maintainability

Example

A reviewer asks for a test covering an empty input rather than simply requesting a rewrite.

Code example

# Useful local review commands:
git diff main...HEAD
git diff --check
git status --short

Diagram

Author diff → reviewer feedback → revision → approval

Key Points

  • Review behavior and risk, not personal style
Q35Repository Governance

What are branch protection rules?

Branch protection rules or rulesets can require pull requests, approvals, status checks, signed commits, linear history, or restrict force pushes…

Answer

Branch protection rules or rulesets can require pull requests, approvals, status checks, signed commits, linear history, or restrict force pushes/deletions. They help prevent unreviewed or failing code from reaching important branches.

Syntax

Require PR + 1 approval + required CI checks

Example

Protect `main` so only reviewed and passing changes can merge.

Code example

# Example policy (configure in GitHub settings):
# main requires pull request
# required status check: test
# disallow force pushes

Diagram

Developer → PR → required checks/approval → protected main

Key Points

  • Align rules with team size and deployment risk
Q36Repository Governance

What are CODEOWNERS files?

A `CODEOWNERS` file maps paths to owners. GitHub can automatically request reviews from those owners, helping route changes to people responsible…

Answer

A `CODEOWNERS` file maps paths to owners. GitHub can automatically request reviews from those owners, helping route changes to people responsible for sensitive or specialized areas.

Syntax

/infra/ @platform-team
/src/payments/ @payments-team

Example

Require payment-service owners to review changes under the payment directory.

Code example

# .github/CODEOWNERS
/src/payments/ @org/payments-team
/.github/workflows/ @org/platform-team

Diagram

Changed path → CODEOWNERS match → review request

Key Points

  • Ensure owners have repository access and maintain the file
Q39CI/CD Fundamentals

Continuous integration vs continuous delivery vs continuous deployment?

Continuous integration frequently integrates changes and validates them automatically. Continuous delivery ensures a release can be deployed with…

Answer

Continuous integration frequently integrates changes and validates them automatically. Continuous delivery ensures a release can be deployed with a deliberate approval. Continuous deployment automatically releases every qualifying change to production.

Syntax

CI: build/test
CDelivery: deployable release + approval
CDeployment: automatic production release

Example

A regulated team may use continuous delivery with a manual production approval.

Code example

# pipeline stages
lint_and_test -> build -> staging -> approval -> production

Diagram

CI → ready artifact; delivery adds release decision; deployment automates production

Key Points

  • The terms differ mainly in the production release decision
Q40GitHub Actions

What is a workflow, job, step, and runner in GitHub Actions?

A workflow is a YAML automation triggered by events. A workflow contains jobs; jobs run on runners and contain steps. Steps run shell commands or…

Answer

A workflow is a YAML automation triggered by events. A workflow contains jobs; jobs run on runners and contain steps. Steps run shell commands or actions and usually execute sequentially within a job.

Syntax

workflow → jobs → steps
runs-on: ubuntu-latest

Example

Use separate jobs for tests and packaging, with a dependency between them.

Code example

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - run: npm ci
      - run: npm test
  build:
    needs: test
    runs-on: ubuntu-latest
    steps:
      - run: npm run build

Diagram

Event → workflow → job runner → ordered steps

Key Points

  • Jobs may run in parallel unless connected with `needs`
Q42GitHub Actions

How do you cache dependencies in GitHub Actions?

Caching reuses dependency downloads or build data between runs. Use a cache key that changes when lockfiles or relevant tool versions change; cac…

Answer

Caching reuses dependency downloads or build data between runs. Use a cache key that changes when lockfiles or relevant tool versions change; caching should improve speed, not replace reproducible installation.

Syntax

key: ${{ runner.os }}-npm-${{ hashFiles('**/package-lock.json') }}

Example

Cache npm's download cache while continuing to install from the lockfile.

Code example

- uses: actions/setup-node@v4
  with:
    node-version: 22
    cache: npm
- run: npm ci

Diagram

Lockfile hash → cache lookup → install missing dependencies

Key Points

  • Use lockfiles and deterministic installs
  • don't cache secrets
Q43Pipeline Security

How do you store secrets in GitHub Actions?

Store credentials in GitHub Actions secrets or environment secrets, scope access narrowly, and avoid printing them. Prefer short-lived federated…

Answer

Store credentials in GitHub Actions secrets or environment secrets, scope access narrowly, and avoid printing them. Prefer short-lived federated credentials such as OIDC when supported instead of long-lived cloud keys.

Syntax

${{ secrets.DEPLOY_TOKEN }}

Example

Use an environment-scoped secret for staging deployment and require approval for production.

Code example

- name: Deploy
  env:
    DEPLOY_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
  run: ./scripts/deploy.sh

Diagram

Secret store → scoped workflow/job → deployment command

Key Points

  • Never hard-code secrets
  • masking is not a substitute for safe logging
Q45GitHub Actions

How do you use a matrix build?

A matrix strategy runs the same job across combinations such as operating systems, runtime versions, or dependency versions. Use it for compatibi…

Answer

A matrix strategy runs the same job across combinations such as operating systems, runtime versions, or dependency versions. Use it for compatibility coverage while controlling total execution cost.

Syntax

strategy:
  matrix:
    node: [20, 22]

Example

Test a library against two supported Node.js versions.

Code example

strategy:
  matrix:
    node-version: [20, 22]
steps:
  - uses: actions/setup-node@v4
    with:
      node-version: ${{ matrix.node-version }}
  - run: npm ci
  - run: npm test

Diagram

One job definition × matrix values → multiple job runs

Key Points

  • Use `fail-fast` and `max-parallel` intentionally
Q46GitHub Actions

How do you pass artifacts between workflow jobs?

Jobs usually run on separate runner instances. Upload build outputs as artifacts in one job and download them in another, or publish immutable ar…

Answer

Jobs usually run on separate runner instances. Upload build outputs as artifacts in one job and download them in another, or publish immutable artifacts to a registry. Avoid rebuilding different bytes for production than were tested.

Syntax

upload-artifact → download-artifact

Example

Build a distributable once, then deploy the same package to staging and production.

Code example

- uses: actions/upload-artifact@v4
  with:
    name: web-build
    path: dist/
# downstream job:
- uses: actions/download-artifact@v4
  with:
    name: web-build
    path: dist/

Diagram

Build job → artifact store → deploy job

Key Points

  • Treat artifacts as versioned release inputs
Q48Automated Testing

What is the testing pyramid?

The testing pyramid recommends many fast unit tests, fewer integration tests, and a smaller number of end-to-end tests. The mix depends on the sy…

Answer

The testing pyramid recommends many fast unit tests, fewer integration tests, and a smaller number of end-to-end tests. The mix depends on the system, but feedback should be fast and failures diagnosable.

Syntax

Unit tests > Integration tests > End-to-end tests

Example

Validate business logic with unit tests, database boundaries with integration tests, and a few critical user journeys end to end.

Code example

# Example test commands
npm run test:unit
npm run test:integration
npm run test:e2e

Diagram

Many unit tests → fewer integration tests → few E2E tests

Key Points

  • Avoid relying solely on slow, brittle end-to-end tests
Q51Automated Testing

What is code coverage, and what are its limits?

Coverage measures which code was executed by tests, commonly line, branch, or function coverage. High coverage does not prove assertions are corr…

Answer

Coverage measures which code was executed by tests, commonly line, branch, or function coverage. High coverage does not prove assertions are correct or edge cases are tested; use it as a signal, not the goal.

Syntax

npm test -- --coverage

Example

Add tests for error branches, not only lines that make the coverage percentage rise.

Code example

# Example Jest configuration output
# Statements: 86%
# Branches: 72%
# Functions: 90%
# Lines: 87%

Diagram

Tests execute paths → coverage report → review uncovered risk

Key Points

  • Branch coverage often reveals untested decision outcomes
Q53Build & Artifacts

What is an artifact in a CI/CD pipeline?

An artifact is a versioned output such as a compiled binary, container image, package, or static site bundle. Promote the same artifact through e…

Answer

An artifact is a versioned output such as a compiled binary, container image, package, or static site bundle. Promote the same artifact through environments to improve traceability and avoid environment-specific rebuild differences.

Syntax

source → build artifact → test → promote

Example

Build a container once and promote its digest from staging to production.

Code example

docker build -t registry.example.com/app:${GITHUB_SHA} .
docker push registry.example.com/app:${GITHUB_SHA}

Diagram

Commit → immutable artifact → staging → production

Key Points

  • Record source revision, dependencies, and artifact digest
Q56Deployment Strategies

What is a rolling deployment?

A rolling deployment gradually replaces instances running the old version with new instances. It reduces the need for a full outage, but the appl…

Answer

A rolling deployment gradually replaces instances running the old version with new instances. It reduces the need for a full outage, but the application must tolerate mixed versions during the rollout.

Syntax

old instances → replace a subset → replace remaining instances

Example

Update a web service across a pool while health checks remove unhealthy instances.

Code example

# Kubernetes-style example
kubectl rollout status deployment/web
kubectl set image deployment/web web=example/web:v2

Diagram

v1 fleet → mixed v1/v2 → v2 fleet

Key Points

  • Ensure readiness probes and backward compatibility
Q57Deployment Strategies

What is a blue-green deployment?

Blue-green deployment maintains two production-like environments. The new version is deployed and validated in the inactive environment, then tra…

Answer

Blue-green deployment maintains two production-like environments. The new version is deployed and validated in the inactive environment, then traffic switches to it. Rollback can switch traffic back if the previous environment remains healthy.

Syntax

Blue active → deploy Green → validate → switch traffic

Example

Deploy v2 to green, run smoke tests, then switch the load balancer.

Code example

# Conceptual commands
./deploy.sh green v2
./smoke-test.sh green
./switch-traffic.sh green

Diagram

Blue (live) + Green (candidate) → traffic switch

Key Points

  • Costs more resources
  • database compatibility still matters
Q59Deployment Strategies

What is a feature flag, and how does it help delivery?

A feature flag separates deploying code from enabling behavior. It can support gradual rollout, experiments, and rapid disablement, but stale fla…

Answer

A feature flag separates deploying code from enabling behavior. It can support gradual rollout, experiments, and rapid disablement, but stale flags create complexity and need ownership and removal plans.

Syntax

if featureFlags.newCheckout:
    showNewCheckout()

Example

Deploy a new checkout path disabled, enable it for internal users, then gradually expand.

Code example

const enabled = await flags.isEnabled("new-checkout", user.id);
if (enabled) {
  return renderNewCheckout();
}
return renderLegacyCheckout();

Diagram

Deploy code → flag off → targeted enablement → full rollout

Key Points

  • Flags are not authorization controls
  • evaluate sensitive access separately
Q61Infrastructure & Delivery

What is Infrastructure as Code (IaC)?

IaC defines infrastructure in version-controlled configuration so environments can be reviewed, reproduced, tested, and changed through controlle…

Answer

IaC defines infrastructure in version-controlled configuration so environments can be reviewed, reproduced, tested, and changed through controlled workflows. Plans should be reviewed before applying destructive changes.

Syntax

terraform fmt
terraform validate
terraform plan

Example

Run a plan on a pull request and apply only after an authorized merge or approval.

Code example

terraform init -input=false
terraform fmt -check
terraform validate
terraform plan -out=tfplan

Diagram

Infrastructure code → plan/review → approved apply

Key Points

  • Protect state files and credentials
  • review drift and destructive plans
Q64Supply Chain Security

What is dependency scanning?

Dependency scanning identifies known vulnerabilities in packages and libraries. Combine lockfiles, automated alerts, risk-based update policies,…

Answer

Dependency scanning identifies known vulnerabilities in packages and libraries. Combine lockfiles, automated alerts, risk-based update policies, and CI checks while evaluating whether a finding is exploitable in the actual application.

Syntax

npm audit
# or ecosystem-specific scanner

Example

Run dependency review on pull requests and block high-risk newly introduced vulnerabilities according to policy.

Code example

npm ci
npm audit --audit-level=high

Diagram

Lockfile/dependencies → vulnerability database → report/policy

Key Points

  • Review false positives and transitive dependency paths
Q66Supply Chain Security

What is an SBOM?

A Software Bill of Materials lists software components and useful metadata such as versions and relationships. It supports vulnerability response…

Answer

A Software Bill of Materials lists software components and useful metadata such as versions and relationships. It supports vulnerability response, inventory, and compliance, but its quality depends on accurate generation and maintenance.

Syntax

generate → validate → publish SBOM

Example

Attach an SBOM to a versioned release artifact for downstream consumers.

Code example

syft registry:example.com/app:1.2.0 -o spdx-json > sbom.spdx.json

Diagram

Artifact → component inventory → consumers/security response

Key Points

  • Generate it for the artifact actually released
Q67Supply Chain Security

How do you scan for secrets in a repository?

Secret scanning searches code and repository history for credential patterns or known tokens. Preventive hooks and CI checks help, but if a secre…

Answer

Secret scanning searches code and repository history for credential patterns or known tokens. Preventive hooks and CI checks help, but if a secret is exposed, revoke or rotate it immediately; deleting the line is not enough.

Syntax

pre-commit scan + CI secret scan

Example

A detected cloud key triggers revocation, rotation, and an audit of its use.

Code example

# Example with an installed scanner
gitleaks detect --source . --redact

Diagram

Commit → secret scanner → pass/fail and remediation

Key Points

  • Treat exposed credentials as compromised
Q71Configuration Management

How do you manage environment variables across stages?

Keep configuration separate from application code, use environment-specific settings for non-secret values, and managed secret stores for credent…

Answer

Keep configuration separate from application code, use environment-specific settings for non-secret values, and managed secret stores for credentials. Validate required settings at startup and avoid baking production secrets into build artifacts.

Syntax

APP_ENV=staging
LOG_LEVEL=info

Example

Deploy the same artifact to staging and production with different runtime endpoints and credentials.

Code example

APP_ENV=staging
API_BASE_URL=https://api-staging.example.com
# credentials injected separately

Diagram

Same artifact + stage configuration → runtime

Key Points

  • Avoid environment-specific rebuilds and secret leakage
Q72Pipeline Design

What are quality gates in a pipeline?

Quality gates are conditions that must pass before the pipeline proceeds, such as tests, linting, coverage thresholds, vulnerability checks, appr…

Answer

Quality gates are conditions that must pass before the pipeline proceeds, such as tests, linting, coverage thresholds, vulnerability checks, approvals, or performance budgets. Gates should focus on actionable risks.

Syntax

lint AND tests AND security scan → eligible

Example

Block deployment if tests fail or a critical policy-defined vulnerability is introduced.

Code example

if tests_pass and scan_pass and approval_granted:
    deploy()
else:
    stop_pipeline()

Diagram

Checks → gate decision → deploy or stop

Key Points

  • Avoid noisy gates that teams routinely bypass
Q78GitHub Actions

How do you handle concurrency and cancel outdated runs?

Concurrency groups can ensure only one run for a given group is active, and `cancel-in-progress` can stop superseded runs. Choose groups carefull…

Answer

Concurrency groups can ensure only one run for a given group is active, and `cancel-in-progress` can stop superseded runs. Choose groups carefully so a newer commit does not cancel a deployment that must finish safely.

Syntax

concurrency:
  group: ci-${{ github.ref }}
  cancel-in-progress: true

Example

Cancel old PR validation when a newer commit is pushed to the same PR branch.

Code example

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

Diagram

New commit → same group → old validation cancelled

Key Points

  • Use separate policies for deployment jobs and critical migrations
Q79Pipeline Design

How do you deploy only from the main branch?

Restrict deployment jobs with branch conditions and environment protection. Branch checks alone are not sufficient for every security boundary; a…

Answer

Restrict deployment jobs with branch conditions and environment protection. Branch checks alone are not sufficient for every security boundary; also control who can change workflow files and who can approve production.

Syntax

if: github.ref == 'refs/heads/main'

Example

Allow production deployment only after a successful workflow on main.

Code example

if: github.ref == 'refs/heads/main'
steps:
  - run: ./deploy-production.sh

Diagram

Validated main commit → protected environment → deploy

Key Points

  • Combine conditions with environment rules and least privilege
Q80Releases & Tags

What is a release pipeline?

A release pipeline packages a known revision, runs release checks, creates version metadata and notes, publishes artifacts, and deploys or promot…

Answer

A release pipeline packages a known revision, runs release checks, creates version metadata and notes, publishes artifacts, and deploys or promotes them according to policy. It should preserve traceability from source commit to running version.

Syntax

tag → validate → package → publish → deploy

Example

Creating tag `v2.3.0` starts release packaging and publishes an immutable artifact.

Code example

on:
  push:
    tags: ["v*.*.*"]
jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - run: echo "Package and publish release"

Diagram

Version tag → build → artifact → release notes/deployment

Key Points

  • Verify the tag points to an approved commit

Advanced Questions

Architecture, optimization, and design trade-offs.

Q29Undo & Recovery

How do you recover a lost commit with reflog?

The reflog records recent local movements of references such as HEAD. It can help recover commits after a reset or branch movement while the obje…

Answer

The reflog records recent local movements of references such as HEAD. It can help recover commits after a reset or branch movement while the objects remain available.

Syntax

git reflog
git branch recovery <commit-id>

Example

A mistaken reset moved the branch away from a useful commit; create a recovery branch from the reflog entry.

Code example

git reflog
# identify the desired commit
git switch -c recovery/fix <commit-id>

Diagram

Reference movement log → prior commit → recovery branch

Key Points

  • Reflog is local and expires
  • act promptly
Q44Pipeline Security

What is the principle of least privilege in CI/CD?

A workflow should receive only the permissions and credentials needed for its task. Set minimal `GITHUB_TOKEN` permissions, separate deployment e…

Answer

A workflow should receive only the permissions and credentials needed for its task. Set minimal `GITHUB_TOKEN` permissions, separate deployment environments, restrict write access, and use protected approvals for production.

Syntax

permissions:
  contents: read

Example

A test-only workflow needs repository read access, not permission to publish releases.

Code example

permissions:
  contents: read
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm test

Diagram

Untrusted PR → read-only validation; trusted release → scoped publish/deploy

Key Points

  • Fork PRs and third-party actions need special scrutiny
Q50Automated Testing

How do you prevent flaky tests?

Flaky tests pass and fail without relevant code changes, often due to timing, shared state, random data, or external dependencies. Make tests det…

Answer

Flaky tests pass and fail without relevant code changes, often due to timing, shared state, random data, or external dependencies. Make tests deterministic, isolate resources, use bounded retries only as a diagnostic aid, and fix root causes.

Syntax

fixed seed + isolated data + explicit waits

Example

Replace arbitrary sleeps in an end-to-end test with a wait for a specific condition.

Code example

# Prefer condition-based waits in test frameworks
await page.getByRole("button", { name: "Save" }).click();
await expect(page.getByText("Saved")).toBeVisible();

Diagram

Flaky failure → classify cause → isolate → fix → verify repeatedly

Key Points

  • Retries can hide reliability problems if used as the solution
Q52Database Delivery

How should database migrations be handled in CI/CD?

Treat migrations as versioned artifacts, test them against representative schemas/data, and plan for compatibility between old and new applicatio…

Answer

Treat migrations as versioned artifacts, test them against representative schemas/data, and plan for compatibility between old and new application versions. Prefer expand-and-contract changes for zero-downtime rollouts.

Syntax

migration up → verify → deploy compatible app → contract later

Example

Add a nullable column first, deploy code that supports both schemas, backfill, then enforce constraints in a later release.

Code example

# Pipeline outline
npm run db:migrate:check
npm run db:migrate:up
npm run test:integration

Diagram

Schema expand → compatible app deploy → backfill → contract

Key Points

  • Backups and rollback plans are essential for risky data changes
Q54Build & Artifacts

What is an immutable deployment artifact?

An immutable artifact is not modified after creation. Deploying the same image digest or package to every environment makes it easier to prove wh…

Answer

An immutable artifact is not modified after creation. Deploying the same image digest or package to every environment makes it easier to prove which bytes were tested and to roll back consistently.

Syntax

image@sha256:<digest>

Example

Deploy a container by digest rather than rebuilding `latest` for production.

Code example

docker build -t registry.example.com/app:${GITHUB_SHA} .
docker push registry.example.com/app:${GITHUB_SHA}
docker inspect registry.example.com/app:${GITHUB_SHA}

Diagram

Build once → immutable digest → promote unchanged

Key Points

  • Avoid mutable tags as the only release identifier
Q58Deployment Strategies

What is a canary release?

A canary release exposes a small portion of traffic or users to a new version, measures health and business metrics, then expands or aborts rollo…

Answer

A canary release exposes a small portion of traffic or users to a new version, measures health and business metrics, then expands or aborts rollout. It limits blast radius but requires reliable observability and traffic control.

Syntax

1% → 5% → 25% → 100%

Example

Send a small traffic share to v2 and halt expansion if error rate rises.

Code example

# Pseudocode
set_traffic("v2", percent=5)
if error_rate("v2") < threshold:
    set_traffic("v2", percent=25)
else:
    rollback("v2")

Diagram

Small cohort → monitor → expand or rollback

Key Points

  • Define abort thresholds before rollout
Q60Deployment Strategies

How do you implement rollback?

Rollback restores a known-good application version or reverses a rollout. It should be rehearsed and account for schema changes, external side ef…

Answer

Rollback restores a known-good application version or reverses a rollout. It should be rehearsed and account for schema changes, external side effects, and data compatibility; a code rollback alone may not undo data mutations.

Syntax

deploy previous artifact
verify health

Example

If v2 fails health checks, redeploy the last known-good image digest and verify key endpoints.

Code example

kubectl rollout undo deployment/web
kubectl rollout status deployment/web
curl -f https://app.example.com/health

Diagram

Release failure → rollback → health verification

Key Points

  • Prefer forward fixes when data changes make rollback unsafe
Q62Pipeline Security

How should secrets be handled in deployment workflows?

Secrets should be injected at runtime from a managed secret store, scoped to a particular environment or job, rotated, and excluded from logs and…

Answer

Secrets should be injected at runtime from a managed secret store, scoped to a particular environment or job, rotated, and excluded from logs and artifacts. Use short-lived identity federation where available.

Syntax

secret manager → runtime environment

Example

Fetch a database credential at deploy time rather than writing it into a repository file.

Code example

# Example: environment injection, not source-code literal
run: ./deploy.sh
env:
  DATABASE_URL: ${{ secrets.DATABASE_URL }}

Diagram

Secret manager → authorized job → process memory

Key Points

  • Limit access, avoid echoing env, rotate exposed credentials
Q63Pipeline Security

What is OIDC federation in CI/CD?

OpenID Connect federation lets a CI workload obtain short-lived cloud credentials based on its identity and claims, often avoiding long-lived clo…

Answer

OpenID Connect federation lets a CI workload obtain short-lived cloud credentials based on its identity and claims, often avoiding long-lived cloud keys stored as secrets. Cloud trust policies must restrict repository, branch, and environment claims.

Syntax

permissions:
  id-token: write
  contents: read

Example

A release workflow exchanges a GitHub Actions OIDC token for a short-lived cloud role session.

Code example

permissions:
  id-token: write
  contents: read
steps:
  - uses: cloud/login-action@v1
    with:
      audience: cloud-provider

Diagram

Workflow identity → OIDC token → trust policy → short-lived role

Key Points

  • Use the cloud provider's documented action and restrictive trust conditions
Q65Supply Chain Security

What is software composition analysis (SCA)?

SCA inventories direct and transitive third-party components, licenses, and known vulnerabilities. It complements static analysis and secret scan…

Answer

SCA inventories direct and transitive third-party components, licenses, and known vulnerabilities. It complements static analysis and secret scanning because it focuses on the software supply chain.

Syntax

generate SBOM → scan components

Example

Produce a Software Bill of Materials for a release and scan it before publishing.

Code example

# Example using an installed SBOM tool
syft dir:. -o cyclonedx-json > sbom.json
grype sbom:sbom.json

Diagram

Dependencies → SBOM → vulnerability/license policy

Key Points

  • Keep tool versions and policies consistent
Q68Supply Chain Security

What is a signed commit or signed release?

Cryptographic signatures help verify that a commit or tag was signed by a trusted key or identity. Signature verification contributes to provenan…

Answer

Cryptographic signatures help verify that a commit or tag was signed by a trusted key or identity. Signature verification contributes to provenance, but trust also depends on key management and policy.

Syntax

git config commit.gpgsign true
git tag -s v1.0.0

Example

Require verified signatures for release tags in a sensitive repository.

Code example

git config --global commit.gpgsign true
git commit -S -m "Update release config"
git tag -s v1.0.0 -m "Release 1.0.0"

Diagram

Commit/tag → signature → verification against trusted identity

Key Points

  • Signatures verify authenticity, not code correctness
Q69Supply Chain Security

What is a software supply-chain attack in CI/CD?

A supply-chain attack compromises dependencies, build tooling, workflow actions, credentials, or release artifacts to affect downstream users. Re…

Answer

A supply-chain attack compromises dependencies, build tooling, workflow actions, credentials, or release artifacts to affect downstream users. Reduce risk with pinned dependencies/actions, least privilege, provenance, review, isolation, and monitoring.

Syntax

pin versions + verify provenance + least privilege

Example

An unpinned third-party action changes unexpectedly; pinning to a reviewed commit reduces this exposure.

Code example

# Prefer reviewed immutable action references:
# uses: owner/action@<full-commit-sha>
# Review upgrades before changing the SHA

Diagram

Source/dependency/action → build environment → artifact → users

Key Points

  • Treat build systems and workflows as production attack surfaces
Q70Supply Chain Security

How do you pin GitHub Actions versions safely?

Pinning an action to a full commit SHA makes the referenced code immutable compared with a moving tag. Pair pinning with Dependabot or an update…

Answer

Pinning an action to a full commit SHA makes the referenced code immutable compared with a moving tag. Pair pinning with Dependabot or an update process so security fixes are reviewed and adopted promptly.

Syntax

uses: owner/action@<full-commit-sha>

Example

Use an approved SHA for checkout and schedule controlled updates.

Code example

steps:
  - uses: actions/checkout@<reviewed-full-commit-sha>
  - run: npm ci

Diagram

Reviewed SHA → workflow run → predictable action code

Key Points

  • Verify publisher and release
  • do not copy unknown SHAs
Q73Pipeline Optimization

How do you speed up a slow CI pipeline?

Measure stage duration first, then parallelize independent jobs, cache dependencies safely, avoid redundant builds, use targeted tests where trus…

Answer

Measure stage duration first, then parallelize independent jobs, cache dependencies safely, avoid redundant builds, use targeted tests where trustworthy, optimize container layers, and cancel superseded runs. Keep correctness and reproducibility intact.

Syntax

profile → parallelize → cache → measure

Example

Run lint and unit tests in parallel while keeping packaging dependent on required checks.

Code example

jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - run: npm run lint
  test:
    runs-on: ubuntu-latest
    steps:
      - run: npm test
  package:
    needs: [lint, test]
    runs-on: ubuntu-latest
    steps:
      - run: npm run build

Diagram

Independent checks in parallel → required gates → package

Key Points

  • Optimize based on data
  • don't skip meaningful tests blindly
Q74Pipeline Architecture

What is a monorepo, and what changes in CI for one?

A monorepo stores multiple packages or services in one repository. CI can use path filters, dependency graphs, and affected-project tests to redu…

Answer

A monorepo stores multiple packages or services in one repository. CI can use path filters, dependency graphs, and affected-project tests to reduce work, while shared changes may require broader validation.

Syntax

changed paths → affected packages → targeted tests

Example

A change to `packages/ui` runs UI and dependent application tests, not unrelated services.

Code example

# Conceptual path filter
if changed("packages/ui/**"):
    test("packages/ui")
    test("apps/web")

Diagram

Changed files → dependency graph → affected test matrix

Key Points

  • Path filters must not skip required checks accidentally
Q75Pipeline Security

How should pull requests from forks be secured?

Fork PRs can contain untrusted code. Avoid exposing secrets or privileged write tokens to workflows that execute that code. Use read-only permiss…

Answer

Fork PRs can contain untrusted code. Avoid exposing secrets or privileged write tokens to workflows that execute that code. Use read-only permissions, isolate untrusted jobs, and avoid unsafe `pull_request_target` patterns that check out and execute attacker-controlled content.

Syntax

permissions:
  contents: read

Example

Run tests on fork PRs without deployment credentials or write access.

Code example

on: pull_request
permissions:
  contents: read
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm ci && npm test

Diagram

Untrusted PR → isolated read-only runner → test results

Key Points

  • Never execute untrusted PR code with privileged secrets
Q76Pipeline Security

What is `pull_request_target`, and why can it be risky?

`pull_request_target` runs in the base repository context and can have access to base-repository secrets and write permissions. Checking out and…

Answer

`pull_request_target` runs in the base repository context and can have access to base-repository secrets and write permissions. Checking out and executing fork-controlled code in that privileged context can create a compromise path.

Syntax

on: pull_request_target

Example

Use it for carefully scoped metadata actions, not for executing untrusted build scripts.

Code example

# Safer baseline for code testing:
on: pull_request
permissions:
  contents: read
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm test

Diagram

Privileged base context + untrusted code = high risk

Key Points

  • Separate metadata workflows from untrusted code execution
Q77GitHub Actions

What are reusable workflows and composite actions?

Reusable workflows share whole job-level pipelines across repositories or teams. Composite actions package a sequence of steps for reuse within j…

Answer

Reusable workflows share whole job-level pipelines across repositories or teams. Composite actions package a sequence of steps for reuse within jobs. Use clear inputs, outputs, permissions, and versioning to prevent hidden coupling.

Syntax

uses: org/repo/.github/workflows/ci.yml@v1

Example

Centralize a standard validation workflow across multiple application repositories.

Code example

jobs:
  call-shared-ci:
    uses: org/engineering/.github/workflows/node-ci.yml@v1
    with:
      node-version: "22"

Diagram

Repository workflow → reusable workflow/action → standardized steps

Key Points

  • Version shared automation and document interface contracts

Share this question bank

Send this page to someone preparing for an interview.