Title: Cicd Pipelines — LearnCoachAssist

Q: What is Continuous Integration (CI)?
A: Continuous Integration is a development practice where developers frequently merge code changes into a shared repository, often multiple times a day. Each merge triggers an automated build and test process to detect integration errors early.
Key benefits:
- Early bug detection
- Reduced integration conflicts
- Faster feedback loops
- Consistent build process

Q: What is the difference between Continuous Delivery and Continuous Deployment?
A: Continuous Delivery ensures code is always in a deployable state but requires a manual approval step before production release.
Continuous Deployment goes further: every change that passes all pipeline stages is automatically deployed to production with no human intervention.
Delivery = ready to deploy on demand
Deployment = auto-deployed every time

Q: What are the typical stages of a CI/CD pipeline?
A: A standard CI/CD pipeline includes these stages:
- Source – code checkout from version control
- Build – compile code and resolve dependencies
- Test – run unit, integration, and end-to-end tests
- Static Analysis – linting, code quality checks
- Security Scan – SAST, dependency scanning
- Package – create deployable artifacts
- Deploy – push to staging or production
- Release – make available to users

Q: What is a GitHub Actions workflow?
A: A GitHub Actions workflow is an automated process defined in a YAML file under .github/workflows/. It is triggered by events such as push, pull_request, or schedule.
A workflow contains one or more jobs, each consisting of steps that run commands or use actions.
Example trigger:
on: [push, pull_request]

Q: What are jobs, steps, and actions in GitHub Actions?
A: - Jobs – independent units of work that run on a runner. Jobs run in parallel by default but can depend on each other using needs.
- Steps – individual tasks within a job, executed sequentially. Each step either runs a shell command (run:) or uses an action (uses:).
- Actions – reusable packaged tasks from the GitHub Marketplace or custom repositories, referenced as uses: actions/checkout@v4.

Q: What are GitHub Actions runners?
A: Runners are servers that execute workflow jobs. GitHub provides:
- GitHub-hosted runners – managed VMs (Ubuntu, Windows, macOS) that are provisioned fresh for each job
- Self-hosted runners – machines you manage yourself, useful for custom hardware, private networks, or cost control
Specified with:
runs-on: ubuntu-latest

Q: What is a matrix build in GitHub Actions?
A: A matrix build runs a job across multiple combinations of variables like OS, language version, or config. It uses the strategy.matrix keyword.
Example:
strategy:
  matrix:
    node: [16, 18, 20]
    os: [ubuntu-latest, windows-latest]
This creates 6 parallel jobs (3 versions × 2 OSes), ensuring compatibility across environments.

Q: What are reusable workflows in GitHub Actions?
A: Reusable workflows allow you to define a workflow once and call it from other workflows using workflow_call.
The called workflow lives in a .github/workflows/ file and declares inputs and secrets.
Caller syntax:
jobs:
  call-workflow:
    uses: org/repo/.github/workflows/ci.yml@main
    with:
      env: production
This promotes DRY principles across repositories.

Q: What is the workflow_dispatch event in GitHub Actions?
A: workflow_dispatch allows you to manually trigger a workflow from the GitHub UI, API, or CLI. You can define custom input parameters.
Example:
on:
  workflow_dispatch:
    inputs:
      environment:
        type: choice
        options: [staging, production]
Useful for ad-hoc deployments and maintenance tasks.

Q: What is a Jenkinsfile?
A: A Jenkinsfile is a text file that defines a Jenkins pipeline using code (Pipeline as Code). It is checked into the repository root.
Two syntax styles:
- Declarative – structured, opinionated syntax with pipeline { } block
- Scripted – flexible Groovy-based syntax with node { } block
Declarative is recommended for most use cases due to readability and built-in validation.

Q: What is the structure of a Declarative Jenkins pipeline?
A: pipeline {
  agent any
  stages {
    stage('Build') {
      steps { sh 'make build' }
    }
    stage('Test') {
      steps { sh 'make test' }
    }
    stage('Deploy') {
      steps { sh 'make deploy' }
    }
  }
}
Key blocks: agent (where to run), stages (what to do), steps (individual commands), and optional post (cleanup/notifications).

Q: What are agents in Jenkins?
A: An agent specifies where a pipeline or stage runs. Options include:
- agent any – run on any available executor
- agent none – no global agent; each stage specifies its own
- agent { label 'linux' } – run on a node with the given label
- agent { docker { image 'node:18' } } – run inside a Docker container
Agents enable distributed builds across multiple machines.

Q: What are Jenkins Shared Libraries?
A: Jenkins Shared Libraries are reusable Groovy code stored in a separate Git repository. They allow teams to share pipeline logic across multiple Jenkinsfiles.
Structure:
- vars/ – global functions callable from pipelines
- src/ – Groovy class files
- resources/ – non-Groovy files
Usage in Jenkinsfile:
@Library('my-shared-lib') _
myCustomStep()

Q: What are build artifacts in CI/CD?
A: Build artifacts are the output files produced during the build process, such as:
- Compiled binaries or JAR files
- Docker images
- Test reports
- Code coverage reports
Artifacts are stored and passed between stages or jobs. In GitHub Actions, use actions/upload-artifact and actions/download-artifact. In Jenkins, use archiveArtifacts.

Q: How does dependency caching work in CI/CD?
A: Dependency caching stores downloaded packages between pipeline runs to avoid re-downloading them each time.
GitHub Actions example:
- uses: actions/cache@v4
  with:
    path: node_modules
    key: deps-${{ hashFiles('package-lock.json') }}
The cache key uses a hash of the lock file so it invalidates when dependencies change. This can reduce build times by 50% or more.

Q: What is build caching and how does it differ from dependency caching?
A: Build caching stores intermediate compilation results (e.g., compiled objects, webpack chunks) to speed up subsequent builds.
Dependency caching stores downloaded packages (node_modules, .m2, pip cache).
Examples of build caches:
- Docker layer caching
- Gradle build cache
- Next.js .next/cache
- ccache for C/C++
Both reduce pipeline time but target different phases of the build.

Q: How are environment variables used in CI/CD pipelines?
A: Environment variables pass configuration values to pipeline steps without hardcoding them.
GitHub Actions:
env:
  NODE_ENV: production
  API_URL: ${{ vars.API_URL }}
Jenkins:
environment {
  NODE_ENV = 'production'
}
They can be set at the workflow, job, or step level and are commonly used for build modes, API endpoints, and feature flags.

Q: How does GitHub Actions manage secrets?
A: GitHub Secrets are encrypted variables stored at the repository, environment, or organization level.
Access in workflows:
${{ secrets.MY_SECRET }}
Key rules:
- Secrets are masked in logs automatically
- They are not passed to workflows from forks by default
- Environment secrets can require reviewers for approval
- Use GITHUB_TOKEN for built-in repo access
Never hardcode secrets in code or workflow files.

Q: What is HashiCorp Vault and how is it used in CI/CD?
A: HashiCorp Vault is a secrets management tool that provides:
- Dynamic secrets – auto-generated, short-lived credentials
- Encryption as a service – encrypt data without storing it
- Secret rotation – automatic credential rotation
- Audit logging – track all secret access
In CI/CD, pipelines authenticate to Vault (via token, AppRole, or OIDC) and fetch secrets at runtime rather than storing them in the CI system.

Q: What is AWS Secrets Manager and when should you use it?
A: AWS Secrets Manager is a service that stores, rotates, and retrieves secrets like database credentials and API keys.
Use it when:
- Your infrastructure runs on AWS
- You need automatic secret rotation
- You want IAM-based access control
- Secrets are consumed by AWS services (Lambda, ECS, RDS)
In CI/CD, use the AWS CLI or SDK to retrieve secrets:
aws secretsmanager get-secret-value --secret-id mySecret

Q: What is blue-green deployment?
A: Blue-green deployment maintains two identical production environments:
- Blue – the current live environment
- Green – the new version being deployed
Traffic is switched from Blue to Green once the new version is verified. If issues occur, you instantly roll back by switching traffic back to Blue.
Pros: zero downtime, instant rollback
Cons: requires double infrastructure, database migrations can be complex

Q: What is canary deployment?
A: Canary deployment gradually rolls out changes to a small subset of users before a full release.
Typical flow:
1. Deploy to 5% of traffic
2. Monitor metrics (error rates, latency)
3. Gradually increase to 25%, 50%, 100%
4. Roll back if metrics degrade
Pros: reduced risk, real-world testing
Cons: requires traffic splitting, needs good monitoring
Tools: Istio, Argo Rollouts, AWS CodeDeploy

Q: What is rolling deployment?
A: Rolling deployment incrementally replaces instances of the old version with the new version, one batch at a time.
Example with 10 servers:
1. Update servers 1-2, verify health
2. Update servers 3-4, verify health
3. Continue until all 10 are updated
Pros: no extra infrastructure needed, gradual rollout
Cons: mixed versions running simultaneously, slower rollback
This is the default strategy in Kubernetes Deployments.

Q: What is the recreate deployment strategy?
A: The recreate strategy shuts down all existing instances before deploying new ones.
Process:
1. Stop all v1 instances
2. Deploy all v2 instances
3. Start v2
Pros: simple, no version compatibility issues, clean state
Cons: causes downtime during the switch
Best for:
- Development/staging environments
- Applications that cannot run multiple versions simultaneously
- Major database schema changes

Q: What is A/B testing deployment?
A: A/B testing deployment routes different user segments to different application versions to compare behavior and outcomes.
Unlike canary (which tests stability), A/B testing measures business metrics:
- Conversion rates
- User engagement
- Revenue impact
Traffic is split based on rules like user ID, geography, or cookies. Requires feature flags or an ingress controller with routing rules.
Tools: LaunchDarkly, Istio, AWS CloudFront

Q: What is GitFlow branching strategy?
A: GitFlow uses multiple long-lived branches:
- main – production-ready code
- develop – integration branch for features
- feature/* – new features branched from develop
- release/* – prepare a release, bug fixes only
- hotfix/* – urgent fixes from main
Pros: structured, clear release process
Cons: complex, long-lived branches can cause merge conflicts
Best suited for projects with scheduled releases.

Q: What is trunk-based development?
A: Trunk-based development has all developers commit to a single main branch (trunk) frequently — at least once per day.
Key practices:
- Short-lived feature branches (1-2 days max)
- Feature flags to hide incomplete work
- Continuous integration with automated tests
Pros: reduces merge conflicts, enables continuous deployment, simpler branching model
Cons: requires discipline, good test coverage, and feature flag management

Q: How do feature branches fit into CI/CD?
A: Feature branches isolate development work in dedicated branches created from the main branch.
CI/CD integration:
- Each push triggers automated builds and tests
- Pull requests run status checks before merging
- Branch protection rules enforce passing CI
- Preview deployments for each PR
Best practices:
- Keep branches short-lived (days, not weeks)
- Rebase frequently from main
- Delete after merging

Q: What is SonarQube and how is it used in CI/CD?
A: SonarQube is a code quality and security analysis platform that inspects code for:
- Bugs – potential runtime errors
- Vulnerabilities – security weaknesses
- Code smells – maintainability issues
- Duplications – repeated code blocks
- Coverage – test coverage percentage
It integrates into CI/CD as a quality gate — the pipeline fails if code doesn't meet defined thresholds (e.g., coverage < 80%).

Q: What are code quality gates in CI/CD?
A: Quality gates are automated checkpoints that enforce minimum standards before code can proceed in the pipeline.
Common quality gates:
- Test coverage ≥ 80%
- Zero critical security vulnerabilities
- No new code smells
- All linting rules pass
- Performance benchmarks within thresholds
If any gate fails, the pipeline blocks the merge or deployment. This ensures consistent code quality across the team.

Q: How is linting integrated into CI/CD pipelines?
A: Linting is integrated as an early pipeline stage to catch style and syntax issues automatically.
Example GitHub Actions step:
- name: Lint
  run: npm run lint
Common linters:
- ESLint – JavaScript/TypeScript
- Pylint / Ruff – Python
- RuboCop – Ruby
- PHP_CodeSniffer – PHP
Best practice: run linting before tests since it's fast and catches obvious issues early.

Q: How do you enforce test coverage thresholds in CI/CD?
A: Test coverage thresholds ensure a minimum percentage of code is tested.
Implementation:
1. Run tests with coverage: jest --coverage
2. Set threshold in config:
"coverageThreshold": {
  "global": { "branches": 80, "lines": 80 }
}
3. Fail the CI step if below threshold
Tools: Jest, Istanbul/nyc, JaCoCo (Java), Coverage.py
Upload reports to SonarQube or Codecov for tracking trends.

Q: What are containerized builds in CI/CD?
A: Containerized builds run pipeline steps inside Docker containers to ensure a consistent, reproducible environment.
Benefits:
- Reproducibility – same environment locally and in CI
- Isolation – no dependency conflicts between projects
- Version control – Dockerfile defines exact tooling
GitHub Actions:
container:
  image: node:18-alpine
Jenkins:
agent { docker { image 'maven:3.9' } }

Q: How do you build and push Docker images in a CI/CD pipeline?
A: Typical steps to build and push a Docker image:
- name: Login to Docker Hub
  run: echo "${{ secrets.DOCKER_PASS }}" | docker login -u ${{ secrets.DOCKER_USER }} --password-stdin
- name: Build image
  run: docker build -t myapp:${{ github.sha }} .
- name: Push image
  run: docker push myapp:${{ github.sha }}
Best practices: tag with commit SHA for traceability, use multi-stage builds for smaller images, and leverage layer caching.

Q: What is SAST (Static Application Security Testing)?
A: SAST analyzes source code without executing it to find security vulnerabilities early in the development cycle.
What it detects:
- SQL injection patterns
- Cross-site scripting (XSS)
- Buffer overflows
- Hardcoded credentials
Popular tools: SonarQube, Semgrep, CodeQL (GitHub), Checkmarx
SAST runs in CI as a build-time check and is best at finding issues in code you write, not in dependencies.

Q: What is DAST (Dynamic Application Security Testing)?
A: DAST tests a running application by simulating attacks from the outside, like a real attacker would.
What it detects:
- Authentication flaws
- Server misconfigurations
- Runtime injection vulnerabilities
- Exposed sensitive data
Popular tools: OWASP ZAP, Burp Suite, Nuclei
DAST runs after deployment to a test environment. It complements SAST by finding runtime issues that static analysis cannot detect.

Q: What is dependency scanning in CI/CD?
A: Dependency scanning checks third-party libraries for known vulnerabilities using databases like the National Vulnerability Database (NVD).
Tools:
- Dependabot (GitHub) – auto-creates PRs for updates
- Snyk – scans and monitors dependencies
- Trivy – scans containers and filesystems
- npm audit / pip-audit – language-specific
Integrate as a CI step to block builds with critical vulnerabilities. Also called Software Composition Analysis (SCA).

Q: How do you set up notifications in CI/CD pipelines?
A: Notifications alert teams about pipeline results. Common integrations:
GitHub Actions:
- uses: slackapi/slack-github-action@v1
  with:
    channel-id: 'C01234'
    slack-message: 'Deploy ${{ job.status }}'
Common channels:
- Slack/Teams – team chat notifications
- Email – build failure alerts
- PagerDuty – production incident alerts
Best practice: notify on failures always, successes only when relevant.

Q: What are approval gates in CI/CD?
A: Approval gates require manual human approval before a pipeline proceeds to the next stage, typically before production deployment.
GitHub Actions: Use environment with required reviewers:
environment:
  name: production
Jenkins:
input message: 'Deploy to production?'
Use cases:
- Production deployments
- Infrastructure changes
- Compliance requirements
Balance between safety and deployment velocity.

Q: What is GitOps?
A: GitOps is a practice where Git is the single source of truth for both application code and infrastructure configuration.
Principles:
- Declarative – desired state described in Git
- Versioned – all changes tracked via commits
- Automated – agents reconcile actual state with desired state
- Observable – drift detection and alerts
Tools: ArgoCD, Flux
Instead of CI pushing deployments, a GitOps agent pulls changes and applies them to the cluster.

Q: How is Infrastructure as Code (IaC) integrated into CI/CD?
A: IaC in CI/CD automates infrastructure provisioning as part of the pipeline:
Typical pipeline stages:
1. terraform fmt -check – validate formatting
2. terraform validate – syntax check
3. terraform plan – preview changes
4. Manual approval gate
5. terraform apply – apply changes
Tools: Terraform, Pulumi, CloudFormation, Ansible
Store state files remotely (S3, GCS) and use state locking to prevent concurrent modifications.

Q: What is the purpose of the build stage in a CI/CD pipeline?
A: The build stage compiles source code and produces executable artifacts.
Activities include:
- Dependency resolution – install packages from lock files
- Compilation – compile TypeScript, Java, Go, etc.
- Bundling – webpack, Vite for frontend assets
- Docker image creation
Best practices:
- Use lock files for deterministic builds
- Enable build caching
- Fail fast on compilation errors
- Produce versioned artifacts

Q: What is the purpose of the test stage in a CI/CD pipeline?
A: The test stage validates code correctness through automated testing.
Test types typically run in CI:
- Unit tests – test individual functions/methods
- Integration tests – test component interactions
- End-to-end tests – test full user workflows
- Smoke tests – basic sanity checks post-deploy
Best practices:
- Run tests in parallel for speed
- Use test splitting across runners
- Generate JUnit XML reports for CI integration

Q: What is the deploy stage in a CI/CD pipeline?
A: The deploy stage releases the built artifact to a target environment.
Common deployment targets:
- Cloud platforms – AWS, GCP, Azure
- Kubernetes clusters
- Serverless – Lambda, Cloud Functions
- PaaS – Heroku, Railway, Fly.io
Best practices:
- Deploy to staging first, then production
- Use environment-specific configs
- Implement health checks after deploy
- Enable automatic rollback on failure

Q: How do you use the needs keyword in GitHub Actions?
A: The needs keyword creates dependencies between jobs, making them run sequentially instead of in parallel.
Example:
jobs:
  build:
    runs-on: ubuntu-latest
    steps: [...]
  test:
    needs: build
    runs-on: ubuntu-latest
  deploy:
    needs: [build, test]
The deploy job waits for both build and test to complete successfully before starting.

Q: What are GitHub Actions environment protection rules?
A: Environment protection rules add safeguards to deployments targeting specific environments.
Available protections:
- Required reviewers – up to 6 people must approve
- Wait timer – delay before deployment (0-43200 minutes)
- Deployment branches – restrict which branches can deploy
- Custom rules – external policy checks
Configured in repo Settings → Environments.
Workflows reference environments with:
environment: production

Q: What are Jenkins pipeline plugins and why are they important?
A: Jenkins plugins extend functionality by adding integrations, build tools, and features.
Essential CI/CD plugins:
- Pipeline – enables Pipeline-as-Code
- Git – source code management
- Docker Pipeline – build inside containers
- Credentials – secure secrets storage
- Blue Ocean – modern UI
- JUnit – test result reporting
Jenkins has 1,800+ plugins. Manage them carefully — too many plugins can cause compatibility and security issues.

Q: How do you handle secrets in Jenkins?
A: Jenkins stores secrets using the Credentials Plugin:
Types:
- Username/Password
- Secret text
- Secret file
- SSH key
- Certificate
Usage in Declarative Pipeline:
environment {
  AWS_KEY = credentials('aws-access-key')
}
Or with withCredentials block:
withCredentials([string(credentialsId: 'token', variable: 'TOKEN')]) {
  sh 'curl -H "Auth: $TOKEN" ...'
}

Q: What is the difference between GitHub-hosted and self-hosted runners?
A: | GitHub-hosted | Self-hosted
Management | GitHub manages | You manage
Environment | Clean VM each job | Persistent
Cost | Included / metered | Your hardware costs
Customization | Limited | Full control
Network | Public internet | Private network access
Use self-hosted for: GPU workloads, private network access, specialized hardware, or cost optimization at scale.

Q: How do you implement multi-environment deployments in CI/CD?
A: Multi-environment deployments promote code through progressively higher environments:
dev → staging → production
Implementation:
- Use environment-specific config files or variables
- Same artifact deployed to each environment
- Approval gates between staging and production
- Environment-scoped secrets
GitHub Actions example:
deploy-staging:
  environment: staging
deploy-prod:
  needs: deploy-staging
  environment: production

Q: What does the SHIPPED environment tier typically mean in a release pipeline?
A: SHIPPED (sometimes called GA / Generally Available) is the final, user-facing production tier where the artifact is available to all end users. Lower tiers (DEV, STAGING, PROD-CANARY) gate access to internal users or a small percentage of real traffic before the artifact reaches SHIPPED status.

Q: What is the purpose of a build number in CI/CD?
A: A build number is a monotonically increasing identifier (e.g., 4231 or 2026.06.22-r17) assigned to each pipeline run. It enables:
- Traceability of which exact artifact is deployed
- Correlation between logs, metrics, and a specific commit
- Reproducible rollback to a known good build
GitHub Actions exposes it as ${{ github.run_number }}; Jenkins provides BUILD_NUMBER.

Q: What is the difference between an artifact and a release in CI/CD?
A: An artifact is the binary output produced by a build (JAR, Docker image, tarball). A release is a named, versioned collection of artifacts plus release notes, typically marked with a Git tag like v1.4.0. Releases are immutable; artifacts are inputs to a release.

Q: What is a build matrix and why would you limit the number of combinations?
A: A build matrix multiplies configurations (Node 16/18/20 × Ubuntu/macOS/Windows = 9 jobs). Limiting combinations is necessary because:
- Each combination consumes CI minutes/cost
- Combinatorial explosion slows feedback
- Diminishing returns when testing exotic combos
Use fail-fast: true to cancel pending matrix jobs when one fails.

Q: What is fail-fast in a build matrix?
A: fail-fast: true (default in GitHub Actions) cancels all in-progress and queued matrix jobs as soon as any one job fails. This saves CI minutes and surfaces the first failure quickly. Set to false if you want to see all failures regardless (e.g., for compatibility reporting across OSes).

Q: What is the max-parallel setting in a build matrix?
A: max-parallel caps how many matrix jobs run concurrently. Useful when you have many combinations but want to throttle resource usage:
strategy:
  matrix: { os: [ubuntu, windows, macOS] }
  max-parallel: 2
Only 2 of the 3 jobs run at a time; the third queues.

Q: What is the purpose of the actions/checkout step?
A: actions/checkout@v4 clones the repository into the runner workspace so subsequent steps can read source code. Key option: fetch-depth: 0 fetches full git history (needed for git blame, tagging, or version detection). Without it, only the triggering commit is checked out (shallow clone).

Q: What is the difference between actions/setup-node and caching node_modules manually?
A: actions/setup-node@v4 with cache: 'npm' automatically caches the npm/yarn/pnpm cache directory using the lockfile hash. Manual caching with actions/cache@v4 is more flexible — you can cache node_modules directly, but you must compute the cache key yourself (e.g., hashFiles('package-lock.json')).

Q: What is a composite action in GitHub Actions?
A: A composite action packages multiple run steps into a single reusable action defined in action.yml. Unlike JavaScript/Docker actions, it does not need a build step and can be authored purely in shell.
Use composite actions to DRY up repeated step sequences like "checkout + setup Node + install deps" across many workflows.

Q: What is the difference between actions/checkout and actions/checkout with persist-credentials?
A: By default, actions/checkout configures a persisted git credential helper on the runner, allowing later steps to push tags, commit, or use authenticated git commands. Setting persist-credentials: false removes the credential helper after checkout, reducing the blast radius if a later step is compromised.

Q: What is the GITHUB_TOKEN and what are its permission scopes?
A: secrets.GITHUB_TOKEN is an automatically provisioned, short-lived token available in every workflow run. Default permission: read/write on the repo where the workflow runs; read-only on others. Scoped via permissions: block:
permissions:
  contents: read
  pull-requests: write
Best practice: grant the least privilege needed.

Q: What is OIDC and how is it used for cloud deployments from CI?
A: OIDC (OpenID Connect) lets your CI provider assume a short-lived cloud IAM role without storing long-lived cloud credentials as secrets. GitHub Actions exposes token: ${{ steps.auth.outputs.token }} from configure-aws-credentials. Benefits: no static AWS keys to leak, automatic credential rotation, auditable per-workflow identity.

Q: How does a step-level if condition work in GitHub Actions?
A: A step can be conditionally executed via:
- name: Deploy to prod
  if: github.ref == 'refs/heads/main'
  run: ./deploy.sh
Common if expressions:
- github.event_name == 'pull_request'
- failure() – run only on failure
- cancelled() – run on cancel
- always() – run regardless of status

Q: What is the difference between github.event and github.event_name?
A: github.event is the full webhook payload (object) for the triggering event. github.event_name is just the name string (e.g., 'push', 'pull_request'). Use event_name for branching logic, and event for accessing event-specific fields like github.event.pull_request.number.

Q: What is the purpose of concurrency in GitHub Actions?
A: concurrency ensures that only one run of a workflow (or group) executes at a time, canceling or queuing the others:
concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true
Prevents wasted CI on superseded pushes and avoids race conditions in deployments.

Q: What is cancel-in-progress and when should you enable it?
A: cancel-in-progress: true aborts any previous in-flight run in the same concurrency group when a new one starts. Enable for: PR builds (only the latest commit matters), feature branch pushes. Disable for: production deployments, long-running release jobs where the older run might be a real release.

Q: What is the difference between schedule and workflow_dispatch triggers?
A: schedule runs the workflow on a cron expression (e.g., cron: '0 2 * * *') and is fired by GitHub's infrastructure — runs may be delayed under load. workflow_dispatch is manually invoked from the UI, CLI, or API and runs immediately. Both can be combined in an on: block.

Q: What is the highest frequency GitHub Actions schedules allow?
A: 5 minutes is the minimum interval — you can schedule with cron: '*/5 * * * *' (every 5 minutes). However, GitHub does not guarantee exact execution time: scheduled runs can be delayed by 3-15 minutes during high load, and missed runs are not backfilled.

Q: What is a workflow_run event and when do you use it?
A: workflow_run triggers a workflow after another workflow finishes. Common pattern: a CI workflow builds on PRs, a separate workflow_run deploys the merged artifact after the CI workflow on the main branch completes successfully. Lets you split CI and CD with different permissions and approvers.

Q: What is the difference between push and pull_request triggers?
A: push fires on commits to the matching branch(es) — including merges that change main. pull_request fires when a PR is opened, synchronized, or reopened. Best practice: run fast CI on pull_request and longer/heavier jobs on push to main, because PRs run on a separate concurrency group and don't affect deployments.

Q: What is a pull_request_target event and why is it dangerous?
A: pull_request_target runs in the context of the target branch (e.g., main) with access to secrets, but is triggered by a PR from a fork. Danger: a malicious PR could run code that exfiltrates secrets.*. Mitigation: never echo attacker-controlled input, and explicitly actions/checkout the PR ref (not the base) only after manual approval.

Q: What is the path filter in GitHub Actions?
A: paths and paths-ignore on on.push (or on.pull_request) restrict when the workflow runs based on which files changed:
on:
  push:
    paths: ['src/**', 'package.json']
Saves CI minutes on doc-only changes; common in monorepos.

Q: What is the difference between a job and a workflow run?
A: A job is a unit of work on a single runner. A workflow run is the overall execution instance triggered by an event, containing all jobs (and their logs, artifacts, statuses). A run is identified by github.run_id; each job has its own github.job name.

Q: What is a service container in GitHub Actions?
A: A service container is a sidecar container started alongside a job to provide a dependency like a database or cache:
services:
  postgres:
    image: postgres:15
    env:
      POSTGRES_PASSWORD: test
    ports: ['5432:5432']
Tests connect to localhost:5432; the container is torn down when the job ends.

Q: How do you drain a self-hosted runner before maintenance?
A: To safely remove a self-hosted runner:
1. Remove the runner from the repo/org (it stops picking up new jobs).
2. Wait for the current job to finish — it shows "Offline" in the runner list when idle.
3. Stop the actions.runner service on the host.
Removing the runner config without stopping the service can leave a "ghost" agent in the GitHub UI.

Q: What is Ephemeral mode in self-hosted runners?
A: An ephemeral runner processes exactly one job, then unregisters and (optionally) tears down the VM. Implemented with --ephemeral flag on the runner config or via GitHub's runner scale sets in Actions Runner Controller (ARC). Improves security by ensuring a clean, untrusted state for each job.

Q: What is the maximum duration of a single GitHub Actions job?
A: The default timeout is 360 minutes (6 hours) per job, configurable via jobs.<id>.timeout-minutes (1-43200 minutes). The overall workflow run timeout default is 35 days but configurable to 1-43200 minutes. Jobs exceeding the timeout are terminated and marked failed.

Q: What is the artifact retention period in GitHub Actions?
A: By default, artifacts are retained for 90 days. You can change this per-artifact with retention-days: on actions/upload-artifact@v4 (1-90 days for public repos, 1-400 for private/enterprise). Older artifacts are auto-deleted. Use Releases or external storage for long-term artifact storage.

Q: What is the purpose of actions/upload-artifact vs actions/download-artifact?
A: upload-artifact stores a file/directory produced by one job so that downstream jobs in the same run (or later, for review) can access it via download-artifact. Common usage: a build job uploads dist/; a deploy job downloads it. Artifacts are not shared across separate workflow runs unless downloaded and re-uploaded.

Q: What is a dynamic matrix in GitHub Actions?
A: A dynamic matrix computes the matrix entries at runtime using the matrix output of a setup job:
jobs:
  setup:
    outputs:
      matrix: ${{ steps.set.outputs.matrix }}
    steps: [id: set, run: echo "matrix={\"node\":$(jq ...)}" >> $GITHUB_OUTPUT]
  test:
    needs: setup
    strategy:
      matrix: ${{ fromJSON(needs.setup.outputs.matrix) }}
Use when the matrix depends on repo state (e.g., changed packages in a monorepo).

Q: What is the continue-on-error property in GitHub Actions?
A: continue-on-error: true on a step or job causes failures to be logged but not propagated — the run continues and a later if: failure() step can react. Useful for non-blocking checks like "send a Slack warning if a flaky test fails" or for collecting diagnostic info before a hard failure.

Q: What is the timeout-minutes property at the job level?
A: timeout-minutes on a job sets a maximum wall-clock duration for the job. If exceeded, the runner cancels the job and marks it failed. Defaults to 360 minutes. Set shorter timeouts (e.g., 10 minutes) for fast feedback jobs to surface hung tests quickly.

Q: What is the difference between a Jenkins agent and a Jenkins executor?
A: An agent (node) is a physical or virtual machine registered with the Jenkins controller. An executor is a slot on an agent that can run one concurrent build. A 4-CPU agent typically has 4 executors. Configure executors via Manage Nodes → Configure → # of executors.

Q: What is the Jenkins controller in a controller-agent architecture?
A: The controller (formerly "master") is the Jenkins server that hosts the configuration, scheduling logic, and UI. Agents (formerly "slaves") are the machines that actually run build jobs. The controller dispatches jobs to agents based on labels, agent availability, and pipeline agent specifications. Jenkins now recommends running agents as containers/pods to scale elastically.

Q: What is the Jenkinsfile directive agent none used for?
A: agent none at the top of a Declarative pipeline disables the global agent, forcing each stage to declare its own agent. This is required when stages need different environments (e.g., one in Linux, one in Windows, one in a Docker container).
pipeline {
  agent none
  stages { stage('Build') { agent { docker 'maven:3.9' } ... } }
}

Q: What is the post section in a Declarative Jenkinsfile?
A: The post section runs steps after all stages complete, with sub-blocks based on result:
post {
  always { cleanWs() }
  success { slackSend 'Build passed' }
  failure { slackSend 'Build failed' }
  unstable { }
  changed { }
}
Common for cleanup, notifications, and reporting.

Q: What is the input step in a Declarative Jenkinsfile?
A: input is the Jenkins manual approval gate:
stage('Deploy') {
  steps {
    input message: 'Deploy to production?', ok: 'Deploy', submitter: 'admins'
    sh './deploy.sh prod'
  }
}
The job pauses until an authorized user clicks the button. Optionally bound to a timeout.

Q: What is a Jenkinsfile when expression?
A: when in Declarative syntax conditionally runs a stage based on branch, environment, or expression:
stage('Deploy to prod') {
  when { branch 'main' }
  steps { sh 'deploy.sh' }
}
Other conditions: environment name: 'DEPLOY', value: 'true', allOf, anyOf, not, tag pattern: 'v\\d+'.

Q: What is a parallel stage in Jenkins?
A: parallel in a Declarative stage runs multiple branches concurrently:
stage('Tests') {
  parallel {
    stage('Unit') { steps { sh 'npm test' } }
    stage('Lint') { steps { sh 'npm run lint' } }
    stage('Typecheck') { steps { sh 'npm run tsc' } }
  }
}
Useful for slicing test time across the same agent or spreading across agents.

Q: What is the difference between Jenkins stash and archiveArtifacts?
A: stash is a per-build, transient file archive shared between stages on the same node; deleted after the build ends. archiveArtifacts is a per-build, persistent file stored on the controller, visible in the build UI, retained per policy, and available across nodes via the artifacts API.

Q: What is the retry step in a Jenkinsfile?
A: retry(3) re-runs the enclosed steps up to 3 times until one succeeds. Common for flaky network operations (npm install, git fetch). Don't retry steps with side effects (e.g., a deploy) — you'll get duplicate executions. Use sleep between retries to let transient issues clear.

Q: What is a Jenkins Credentials binding and which scopes exist?
A: Credentials in Jenkins are scoped:
- System – visible to all jobs (use sparingly)
- Global (default) – visible across folders/agents
- Folder – scoped to a Jenkins folder
withCredentials binds a credential to an env var within a block, ensuring the secret is masked in console output.

Q: What is a multibranch pipeline in Jenkins?
A: A multibranch pipeline auto-discovers Jenkinsfiles in every branch of a repo and creates a separate pipeline job per branch. New branches → new jobs; deleted branches → jobs removed. PRs are also supported via the multibranch + branch source plugin. The replacement for the older "GitHub Organization Folder" pattern.

Q: What is the difference between a Pipeline job and a Freestyle job in Jenkins?
A: A Freestyle job is a GUI-configured job (checkboxes, text fields) — limited reusability, no version control on the job config. A Pipeline job uses a Jenkinsfile defined as code, versioned with the repo, supports complex logic, parallel stages, and reusability. New projects should use Pipeline.

Q: What is a Jenkins Shared Library version?
A: Shared Libraries can have multiple branches/tags loaded by different Jenkinsfiles via the @Library('my-lib@1.4.0') _ syntax. Use immutable tags (not branch names) in production Jenkinsfiles so an admin mistake can't change what runs in your pipeline.

Q: What is the purpose of the Jenkins Cron syntax?
A: triggers { cron('H 2 * * *') } schedules a Declarative pipeline using a cron-like expression. The H (hash) prefix spreads the load across the hour (H/15 * * * * = every 15 min, jittered) to avoid all jobs firing at :00. Useful for nightly builds, cleanup, dependency updates.

Q: What is the GitLab CI .gitlab-ci.yml file?
A: .gitlab-ci.yml at the repo root defines GitLab CI/CD pipelines as YAML. It contains:
- Stages – groups of jobs (build, test, deploy)
- Jobs – units of work in a stage; jobs in a stage run in parallel
- Variables, before_script, after_script
- Rules – conditions for inclusion/exclusion
GitLab auto-detects the file and creates a pipeline on every push.

Q: What is the difference between GitLab CI and Jenkins in pipeline-as-code?
A: GitLab CI tightly integrates with the GitLab repo UI: pipeline runs, logs, artifacts, environments, and merge-request widgets are first-class. Jenkins is repo-agnostic and integrates with any SCM via plugins. GitLab CI uses YAML in-repo; Jenkins uses Groovy (Declarative/Scripted) in-repo.

Q: What is a GitLab CI runner?
A: A runner is an agent process that executes pipeline jobs. Runners are tagged (e.g., docker, linux, gpu) and jobs target them with tags: [docker]. Types: Shared (across the GitLab instance), Group (within a group), Project (specific repo), Specific (one runner, one project).

Q: What is the GitLab CI artifacts keyword?
A: artifacts: declares files to attach to a job and pass to downstream jobs in the same pipeline:
test:
  script: npm test
  artifacts:
    paths: [coverage/]
    expire_in: 1 week
expire_in sets retention. reports: sub-key (junit, cobertura, dotenv) adds special parsed reports.

Q: What is the GitLab CI needs keyword?
A: needs: creates directed acyclic graph (DAG) dependencies between jobs, allowing non-stage-order execution:
deploy:
  stage: deploy
  needs: [build, test]
  script: ./deploy.sh
Unlike stage ordering, needs lets deploy run as soon as its specific inputs are ready, reducing pipeline time.

Q: What is the GitLab CI rules keyword?
A: rules: is the modern, flexible replacement for only/except. It supports complex conditions:
deploy:
  rules:
    - if: $CI_COMMIT_BRANCH == "main"
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
Use when: manual, when: delayed, when: never to control inclusion.

Q: What is the difference between a CircleCI executor and a step?
A: An executor is the runtime environment for a job: docker, machine (full VM), macos, windows, or self-hosted. A step is an individual command or action within a job, like - run: npm test or - checkout. Jobs run on executors; steps are units of work within a job.

Q: What is CircleCI orbs?
A: Orbs are reusable packages of CircleCI configuration (jobs, commands, executors) published to the Orb Registry. Example: circleci/node@5 sets up Node, caches npm, and runs common tasks. Orbs are CircleCI's analog of GitHub Actions marketplace actions and Jenkins shared libraries.

Q: What is the CircleCI contexts feature?
A: Contexts are groups of environment variables and secrets shared across projects. Example: a prod-aws context holds AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY and is restricted to the infrastructure project. Jobs opt in via context: prod-aws. Replaces per-project env-var sprawl.

Q: What is the difference between Bitbucket Pipelines and GitHub Actions?
A: Both are repo-integrated, YAML-defined pipelines. Differences:
- Bitbucket Pipelines is cloud-only (no self-hosted runners for the cloud product, except self-hosted runners since 2023); GH Actions has both cloud and self-hosted.
- Bitbucket's bitbucket-pipelines.yml has a simpler syntax; GH Actions is more expressive.
- Bitbucket Deployments are a first-class concept with built-in environment tracking.

Q: What is the Travis CI .travis.yml format?
A: Travis CI uses .travis.yml with top-level keys: language, dist, install, script, deploy, stages, jobs. Modern Travis is configured as stages with parallel jobs. The original Travis (org) is largely deprecated; travis-ci.com is the supported successor with Linux/macOS/Windows.

Q: What is a Buildkite pipeline and how does it differ from GitHub-hosted CI?
A: Buildkite uses a hybrid model: the orchestration (pipelines, UI, secrets) runs on Buildkite's cloud, but agents run on your own infrastructure. You retain control of build secrets, hardware, and scale, while Buildkite handles scheduling and the web UI. Pipeline definitions live in a pipeline.yml file in the repo.

Q: What is Drone CI and what is its key abstraction?
A: Drone is a container-native CI/CD platform whose core abstraction is each pipeline step runs in its own Docker container by default. .drone.yml defines a list of steps, each with a image: to run in. This makes builds fully reproducible and easy to test locally with the same Docker images.

Q: What is the difference between Drone and Tekton?
A: Drone is a CI/CD product with a fixed pipeline model (YAML, Docker steps). Tekton is a CNCF framework for building CI/CD systems on Kubernetes, exposing low-level primitives (Task, TaskRun, Pipeline, PipelineRun) as Kubernetes CRDs. Tekton is more flexible but requires Kubernetes expertise; Drone is simpler but less customizable.

Q: What is the difference between Jenkins, GitHub Actions, and Tekton at a high level?
A: | Jenkins | GitHub Actions | Tekton
Hosting | Self-hosted | Cloud-first | Kubernetes-native
Pipeline syntax | Groovy (Jenkinsfile) | YAML (workflow) | YAML CRDs
Extensibility | 1800+ plugins | Marketplace actions | Custom Tasks
UI | Blue Ocean | GitHub.com | Dashboard / CLI
Multi-cloud CD | Plugins | 3rd-party | 3rd-party
All three implement pipeline-as-code.

Q: What is a pipeline as code benefit beyond version control?
A: Pipeline as code (Jenkinsfile, workflow YAML) gives you
- Code review for pipeline changes (PR review of CI changes)
- Testing of pipeline definitions
- Reuse across branches and forks
- Audit trail of who changed the build process and why
- Disaster recovery — pipeline is in git, not lost with the controller
Just like application code, your CI definition deserves review.

Q: What is the difference between a status check and a check run on GitHub?
A: Status checks (legacy) are tied to a commit SHA and submitted via the Statuses API — simple pass/fail. Check runs (Checks API) are richer: they support annotations, multi-step outputs, images, deployment records, and are what GitHub Actions uses by default. Actions uses Check Runs; many external CI systems now also use them.

Q: What is the difference between required and optional status checks?
A: On a protected branch, required status checks must pass before merging is allowed. Optional status checks appear in the PR UI but don't block merge. Configure via Branch protection rules → "Require status checks to pass before merging". This is the foundation of enforced CI.

Q: What is a monorepo CI challenge?
A: In a monorepo, a single PR can touch many services. Naive CI builds all packages on every PR, wasting time. The fix is affected-target detection using tools like Nx, Turborepo, Bazel, or Buck to compute the dependency graph and run only the impacted test/build targets.

Q: What is Bazel and how does it integrate with CI?
A: Bazel is Google's remote-cache, hermetic build system. CI integration:
- Remote cache (--remote_cache) — build outputs cached across CI runs and developer machines
- Remote execution (--remote_executor) — distribute compilation to a build farm
- Hermeticity guarantees identical results locally and in CI
Common in monorepos with mixed languages (Java, Go, TS, Python).

Q: What is Turborepo and what problem does it solve?
A: Turborepo is a build orchestrator for JavaScript/TypeScript monorepos. It uses the turbo.json pipeline graph and a content-addressable cache (.turbo/cache or remote cache) to skip work whose inputs haven't changed. CI integration: turbo run test --filter=...[origin/main] runs only tests affected by the PR.

Q: What is remote build caching and how does it save CI time?
A: Remote build caching lets a CI job reuse build outputs from previous runs (and from teammates' machines) via a shared cache. Bazel, Nx, and Turborepo all support it. Typical savings: a fresh CI build for a 5-package monorepo taking 25 minutes drops to under 3 minutes when 4 of 5 packages are cache hits.

Q: What is the test pyramid and how does it shape CI?
A: The test pyramid has many unit tests at the base, fewer integration tests in the middle, and very few E2E tests at the top. CI mirrors it:
1. Fast unit tests on every commit
2. Integration tests after build
3. E2E tests against staging
Running the full pyramid on every commit is wasteful; tier it.

Q: What is flaky test quarantine?
A: A flaky test quarantine is the practice of isolating known-flaky tests into a separate CI suite that runs less frequently or is excluded from required status checks. Each quarantined test has an owner and a ticket. Goal: stop flakes from blocking PRs while still surfacing them.

Q: What is test parallelization and what are its limits?
A: Test parallelization splits a test suite into shards that run simultaneously. Limits:
- Some tests share state (DB, file system) and must run serially
- Cost: each parallel runner consumes CI minutes
- Diminishing returns past 8-10x parallel
- Order-dependent tests break under parallel execution
Tools: pytest-xdist, Jest --shard, Knapsack (Ruby).

Q: What is a canary analysis in Spinnaker?
A: Canary analysis in Spinnaker compares metrics between baseline (old) and canary (new) deployments over a configured time window. It can use automated judgments (statistical comparison via Kayenta) or manual judgments (human in the loop). The pipeline proceeds or rolls back based on the verdict.

Q: What is Kayenta?
A: Kayenta is the automated canary analysis engine used by Spinnaker (originally from Netflix). It pulls metrics (from Prometheus, Datadog, Stackdriver, etc.), compares the canary and baseline distributions using statistical tests (e.g., Jensen-Shannon divergence), and produces a score 0-100. Pipeline advances or rolls back based on the score.

Q: What is a feature flag service like LaunchDarkly or Flagsmith?
A: Feature flag services let you toggle code paths at runtime without redeploying:
- LaunchDarkly – SaaS, targeting rules, experimentation
- Flagsmith – open-source + SaaS
- Unleash – open-source
- GrowthBook – open-source with A/B testing
CI/CD integration: a flag is off in production by default; flip it on via the dashboard, not via deploy.

Q: What is progressive delivery?
A: Progressive delivery is the umbrella term for gradual rollout strategies (canary, blue/green, feature flags, dark launches). Goal: reduce blast radius of new releases by exposing them to increasingly larger audiences with automated safety checks (metrics, error budgets). It's a superset of continuous deployment.

Q: What is a service mesh and how does it enable canary?
A: A service mesh (Istio, Linkerd, Consul) sits at the sidecar of every pod, giving you fine-grained traffic control without app changes. To canary:VirtualService:
  hosts: [my-service]
  http:
    - route: [{destination: {subset: v1}, weight: 95}, {destination: {subset: v2}, weight: 5}]
The mesh routes 5% to v2, then ramps up.

Q: What is Argo Rollouts?
A: Argo Rollouts is a Kubernetes controller that extends Deployments with progressive delivery strategies (canary, blue/green, experiment). It supports automated analysis (Prometheus queries) and traffic splitting via Service mesh (Istio) or ingress (NGINX, ALB). Replaces the standard Deployment when you need real canary/blue-green semantics in k8s.

Q: What is the difference between ArgoCD and Argo Rollouts?
A: ArgoCD is a GitOps continuous-delivery controller — it watches Git repos and syncs cluster state to match. Argo Rollouts is a progressive-delivery controller — it manages the rollout of a new version using canary/blue-green. They are complementary: ArgoCD applies the new ReplicaSet definition, and Argo Rollouts drives the gradual traffic shift.

Q: What is Flux CD?
A: Flux CD is a GitOps toolkit for Kubernetes (CNCF graduated). It watches Git repos for changes to manifests or Helm charts and reconciles cluster state. Flux vs ArgoCD: Flux is more modular (CLI + controllers), better for platform teams; ArgoCD has a richer web UI and is friendlier to app teams.

Q: What is a Helm chart in CI/CD?
A: A Helm chart packages Kubernetes manifests as a templated, versioned artifact. In CI/CD:
1. CI builds a chart and pushes to a Helm registry (OCI artifact in GHCR/ECR)
2. CD layer (ArgoCD/Flux) deploys by referencing the chart version
helm template / helm lint run in CI validate the chart before packaging.

Q: What is the difference between build once and deploy many?
A: Build once, deploy many is a principle: compile/package the artifact once in CI, then promote the same artifact through staging → canary → production. Avoids "works on my machine" drift and "the deploy that just passed is not the deploy that's in prod". Contrast: rebuilding per environment leads to subtle differences.

Q: What is an immutable tag in container CI/CD?
A: An immutable tag (e.g., a Git SHA like myapp:abc1234) is a tag that never changes once pushed. Mutable tags like latest or stable can be overwritten, causing non-reproducible deployments. Best practice: use SHA tags for rollouts, and only use latest for local dev convenience.

Q: What is the purpose of a digest pin in container deployments?
A: A digest is the content-addressable hash of an image (e.g., sha256:abc123...). Pinning deployments to a digest (not a tag) guarantees the running image is byte-for-byte the one CI built — even if a tag is overwritten. Kubernetes manifests can reference image: myapp@sha256:abc123 for full reproducibility.

Q: What is the difference between ephemeral runners and container-based CI?
A: Ephemeral runners (e.g., GitHub Actions self-hosted ARC, Buildkite agents) spin up a fresh VM/container per job and tear it down — no shared state. Container-based CI like GitHub Actions' hosted runners also use fresh VMs, but the job steps still share a runner. Ephemeral models add an outer clean-slate wrapper for stronger isolation.

Q: What is a Software Bill of Materials (SBOM)?
A: An SBOM is a machine-readable list of every component in a software artifact: libraries, versions, licenses, hashes. Formats: SPDX, CycloneDX. CI/CD generates SBOMs at build time (e.g., syft myapp:latest) for vulnerability tracking, license compliance, and supply-chain transparency. Increasingly required by regulation (US EO 14028).

Q: What is SLSA (Supply-chain Levels for Software Artifacts)?
A: SLSA is a security framework with levels (1-4) for supply-chain integrity. Level 1: provenance documentation. Level 2: signed provenance from a hosted build platform. Level 3: hardened build platform resistant to runner compromise. Level 4: hermetic, reproducible, two-party review. CI/CD adoption: signed builds, attestation via Sigstore, hardened runners.

Q: What is Sigstore and what problem does it solve?
A: Sigstore is a toolset for signing and verifying software artifacts (containers, binaries, SBOMs). Components: cosign (sign), rekor (transparency log), fulcio (cert authority for short-lived certs). Solves: key management for code signing — no need to manage long-lived signing keys; instead, identities are bound to OIDC tokens.

Q: What is cosign and how is it used in CI/CD?
A: cosign is the Sigstore signing CLI. In CI:
cosign sign --keyless ghcr.io/myorg/myapp:${{ github.sha }}
Admins verify on deploy with cosign verify. Keyless mode uses OIDC (GitHub, Google) for ephemeral signing identities, recorded in the public rekor transparency log for non-repudiation.

Q: What is a policy engine in supply-chain security?
A: Policy engines (e.g., OPA/Gatekeeper, Kyverno, Conftest) evaluate declarative rules against inputs. In CI/CD, they gate promotions: "block deploy unless image is signed", "block deploy if SBOM contains GPL-licensed code". Policies are versioned in Git, auditable, and testable like code.

Q: What is the principle of least privilege in CI/CD?
A: Grant each CI job, runner, and IAM role the minimum permissions required for its work:
- permissions: read-all in GitHub Actions, then escalate per-job
- Per-environment IAM roles, not one mega-role
- Read-only deploy tokens where possible
- Use OIDC federation instead of long-lived secrets
Reduces blast radius if a job is compromised.

Q: What is the principle of immutable infrastructure?
A: Immutable infrastructure means servers/containers are never modified in place — every change is a new build replacing the old. Combined with CI/CD: a new commit → new image → new VM/container → load balancer shift. Benefits: consistent environments, no configuration drift, easy rollback (just redeploy the previous image).

Q: What is a pipeline as code linter?
A: Pipeline-as-code linters catch syntax and logic errors before a workflow runs:
- actionlint for GitHub Actions
- yamllint for general YAML
- Jenkins pipeline lint via the pipeline-linter API or Jenkinsfile in PRs
- GitLab CI Lint tool
Run them as a fast pre-merge check; faster feedback than waiting for CI.

Q: What is the Jenkins pipeline-linter endpoint?
A: The Jenkins pipeline-linter REST endpoint (/pipeline-model-converter/validate) validates a Jenkinsfile against the controller's installed plugins. Use in PRs via:
curl -X POST -F "jenkinsfile=<Jenkinsfile" https://jenkins.example.com/pipeline-model-converter/validate
or via the CLI plugin. Catches syntax errors before a real build attempt.

Q: What is the difference between webhooks and polling in CI?
A: Webhooks are push notifications from GitHub/GitLab to the CI server on every push — instant, low overhead. Polling is the CI server periodically git fetch-ing to detect changes — slower, wastes resources. Always prefer webhooks; use polling only as a fallback for SCMs without webhook support.

Q: What is pipeline caching of Docker layers?
A: Docker layer caching stores intermediate image layers between builds:
cache-from: type=gha / cache-to: type=gha,mode=max in docker/build-push-action@v5
The build pushes layers to the GitHub Actions cache; subsequent builds --cache-from them. For 5x-10x speedups when only the last layer (app code) changes.

Q: What is the difference between Kaniko, Buildah, and docker buildx?
A: All build container images without a Docker daemon, useful in CI:
- Kaniko – builds in-container, no daemon, runs in k8s natively
- Buildah – CLI alternative to docker build, daemonless, supports OCI
- docker buildx – official BuildKit frontend, supports multi-platform builds, cache export
Choose buildx for most cases; kaniko inside cluster pods; buildah for daemonless systems.

Q: What is multi-platform image building?
A: Multi-platform (multi-arch) images bundle binaries for several CPU architectures (amd64, arm64, arm/v7) in a single tag:
docker buildx build --platform linux/amd64,linux/arm64 -t myapp:$SHA --push .
Useful for shipping the same image to Intel servers and ARM (Graviton, M1/M2, Raspberry Pi) without per-arch images. Implemented with manifest lists.

Q: What is ephemeral preview environments?
A: Ephemeral preview environments are short-lived, per-PR deployments for review. Tools: Vercel, Netlify, Render, Heroku Review Apps, Gitpod, or custom (ArgoCD PR apps). Each PR gets a unique URL, deployed automatically, destroyed on merge/close. Drastically improves design review and integration testing.

Q: What is a canary release compared to a beta release?
A: A canary release is infrastructure-controlled (e.g., 1% of production traffic) and internal — users may not know. A beta release is user-opted-in (TestFlight, Google Play beta track) and serves users who explicitly signed up. Canary measures stability; beta collects user feedback on new features.

Q: What is dark launching?
A: Dark launching deploys a new code path behind a feature flag and exercises it with real production traffic (writes, calls, etc.) without exposing the output to users. It validates that the new code works at production scale before any user-visible change. Common in big rewrites (Twitter's "fail whale" rebuild used this).

Q: What is a release train in software delivery?
A: A release train is a fixed-cadence schedule (e.g., every Tuesday at 10:00) at which new code is released. Features either make the train or wait for the next. Benefits: predictable ops load, easier coordination. Drawbacks: pressure to "make the train" can lead to rushed features or rollback. Common in regulated industries.

Q: What is the difference between a hotfix and a rollback?
A: A hotfix ships a new artifact with a bug fix. A rollback re-deploys a previous, known-good artifact with no code change. Hotfix = forward fix; rollback = revert to last working state. CI/CD should support both: rollback for immediate mitigation, hotfix for a permanent solution.

Q: What is the average time to recover (MTTR) in a CI/CD context?
A: MTTR (Mean Time To Recover / Restore) is the average time from incident detection to service restoration. Strong CD practices (immutable artifacts, fast rollback, canary analysis) drive MTTR down to minutes. DORA's Elite performers report MTTR under one hour; low performers take days. CI/CD is the primary lever.

Q: What is a deployment freeze?
A: A deployment freeze blocks production deployments during high-risk windows (holidays, Black Friday, end-of-quarter). Implemented in CI/CD via rules: - if: $DEPLOY_FREEZE == 'true' or pipeline-level guard. Forces a discussion before override. Avoid freezes by improving release safety, not by gating velocity.

Q: What is change failure rate (CFR) in DORA metrics?
A: Change Failure Rate (CFR) is the percentage of changes (deploys, releases) that result in degraded service or require remediation (rollback, hotfix, incident). DORA's Elite performers achieve 0-15%; low performers 46-60%. CI/CD practices that lower CFR: small batches, trunk-based dev, automated tests, canary releases.

Q: What is lead time for changes in DORA metrics?
A: Lead time for changes measures from code commit to code in production. DORA's Elite performers achieve less than one hour. Influenced by CI/CD build/test speed, approval gates, and the maturity of the deploy pipeline. Trunk-based development and self-service deploys dramatically shorten lead time.

Q: What is deployment frequency in DORA metrics?
A: Deployment frequency counts how often an organization deploys to production. Elite performers: on-demand (multiple per day). Low performers: between once per month and once per six months. Higher frequency correlates with lower CFR and shorter MTTR — small, frequent changes are safer.

Q: What is a flaky test in CI?
A: A flaky test is one that passes and fails intermittently on the same commit, usually due to timing, concurrency, or shared state. Flakes are CI's #1 productivity killer: engineers stop trusting "red" builds. Fixes: isolate the test, use deterministic inputs, avoid sleep(), mock time, retry with caution. Track flake rate as a KPI.

Q: What is a pre-commit hook?
A: A pre-commit hook runs locally before git commit completes, typically for fast checks (lint, format, type-check). It catches issues before CI, saving round-trip time. Implemented with Husky, pre-commit.com, lefthook. Don't run slow tests in pre-commit — keep it under 5 seconds.

Q: What is pre-commit and the pre-commit framework?
A: pre-commit is a framework for managing multi-language git hooks via a .pre-commit-config.yaml file. Each hook is a managed environment (Python, Node, etc.) that auto-installs in its own venv. Examples: black, flake8, eslint, shellcheck, detect-secrets. Hooks run in parallel.

Q: What is the difference between pre-commit and CI?
A: pre-commit is local, fast, and bypassable (developers can --no-verify). CI is the authoritative gate that runs on the server with no possibility of bypass. Use pre-commit for developer experience (fast feedback, autoformat on save); use CI as the enforcer for what must be true.

Q: What is the difference between composite and reusable workflow?
A: - Composite action — a reusable step (multiple shell commands), called with uses:
- Reusable workflow (workflow_call) — a reusable workflow with its own jobs, called with uses: at job level
Composite = step-level reuse; reusable workflow = multi-job reuse. Both promote DRY across repositories.

Q: What is the difference between actions/cache and actions/upload-artifact?
A: actions/cache is a build-time accelerator keyed on inputs (lockfile hash); restored on cache hit, generated on miss; not exposed in the UI for download. actions/upload-artifact is a deliverable: a named bundle (test reports, binaries) downloadable from the run UI, retained per policy, shareable across runs. Caching speeds up; artifacts record results.

Q: What is the GitHub Actions billing model?
A: GitHub Actions bills by minutes consumed per runner type:
- Linux: 1x multiplier (e.g., $0.008/min on Team)
- Windows: 2x
- macOS: 10x
Free tier: 2,000 min/month for private repos. Storage: artifact & cache storage has its own GB-month price.

Q: What is a self-hosted runner auto-scaler?
A: Auto-scalers dynamically provision self-hosted runners based on job queue depth:
- actions-runner-controller (ARC) on Kubernetes
- Buildkite Elastic CI on AWS
- GitLab Runner with autoscaler driver
- CircleCI runner + Nomad
Scales from 0 to N runners; reduces idle compute cost.

Q: What is Actions Runner Controller (ARC)?
A: ARC is a Kubernetes operator that runs GitHub Actions self-hosted runners as pods via the actions.summerwind.dev/v1alpha1 CRDs (RunnerDeployment, HorizontalRunnerAutoscaler). It supports ephemeral runners (one job per pod), labels, and scales based on workflow backlog. The modern way to scale Actions in k8s.

Q: What is the difference between a webhook event and a workflow_dispatch API call?
A: Both can trigger workflows, but:
- A webhook event (push, pull_request) is event-driven by the SCM, originating from a git action.
- workflow_dispatch is intentional and synchronous, invoked via UI / gh workflow run / REST API.
Use webhooks for reactive automation; use dispatch for manual/operational jobs.

Q: What is the difference between set -e and set -euo pipefail in shell steps?
A: In CI shell steps:
- set -e — exit on first error
- set -u — error on undefined variables
- set -o pipefail — pipeline fails if any command in the pipe fails (not just the last)
Default GitHub Actions shell is bash --noprofile --norc -eo pipefail {0} on Linux, so pipefail is on by default. Explicitly adding set -euo pipefail documents intent and is portable.

Q: What is the difference between run: and run: | in YAML?
A: Single-line run: echo hello is one command. Block scalar run: | starts a multi-line string. The indentation of the lines below the pipe is significant — they form one block passed to the shell. Use | (literal newlines preserved) vs > (folded into one line with spaces) for shell commands.

Q: What is the default working directory in GitHub Actions?
A: The default working directory is GITHUB_WORKSPACE (actions/checkout clones the repo here). For self-hosted runners it's the runner's start directory. Override with working-directory on a step or job defaults.run.