Pipeline design & Jenkinsfile decisions
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q1 A team's PR builds pile up: every push to an open PR starts a new 25-minute build while the old one keeps running. What do you change?
Beginner
Situation read โ Outdated builds waste executors and pods; only the newest commit matters for a PR.
What I'd do โ
- Add to the Jenkinsfile:
options { disableConcurrentBuilds(abortPrevious: true) } - Confirm the branch source discovers PRs and excludes branches filed as PRs, so each push builds once.
- Keep
mainbuilds unaborted if every commit must be built:disableConcurrentBuilds(abortPrevious: env.BRANCH_NAME != 'main').
Why โ abortPrevious cancels the running build of the same job when a new one starts, freeing capacity immediately.
Interview tip โ Mention that each PR is its own child job in multibranch, so this only affects builds of the same PR.
Q2 A deploy pipeline waits on input for approval, and on Monday you find 14 pods sitting idle since Friday. Fix it.
Intermediate
input for approval, and on Monday you find 14 pods sitting idle since Friday. Fix it.Situation read โ The input step is inside a stage that holds an agent, so each waiting build keeps a pod (and its resource requests) alive.
What I'd do โ
- Use
agent noneat the top and give build stages their own agent. - Move the approval to a stage-level
inputdirective with no agent and a timeout:stage('Approve prod') { options { timeout(time: 8, unit: 'HOURS') } input { message 'Deploy to prod?'; submitter 'release-managers' } steps { echo 'Approved' } } - Run the actual deploy in the next stage with its own deploy pod.
- Add
milestone()orabortPreviousso an older build cannot be approved after a newer one.
Why โ Waiting on the controller costs nothing; waiting inside an agent costs a pod per build.
Interview tip โ Always say "timeout on every input"; unbounded approvals are a classic Jenkins smell.
Q3 Unit tests, lint, dependency audit and SAST run sequentially and take 22 minutes. How do you restructure the pipeline?
Beginner
Situation read โ These checks are independent and can run concurrently.
What I'd do โ
- Put them under one
parallelstage withfailFast true. - If they share one pod, run them as parallel branches using different containers; if heavy, give each branch its own agent.
- Run the fastest check (lint, under 1 minute) also as a separate first stage so obvious failures stop the build before pods spin up.
stage('Checks') { failFast true; parallel { stage('Unit') { steps { container('node') { sh 'npm test' } } } stage('Audit') { steps { container('node') { sh 'npm audit --audit-level=high' } } } stage('SAST') { steps { container('semgrep') { sh 'semgrep ci' } } } } }
Why โ Wall time becomes the slowest branch instead of the sum.
Interview tip โ Quote numbers: "22 minutes down to 8, the longest branch".
Q4 Developers want to rerun only the deploy stage when it fails due to a flaky cluster API, without rebuilding the image. What do you offer?
Intermediate
Situation read โ Rebuilding is slow and produces a different artifact; we want to retry with the same image.
What I'd do โ
- Ensure the deploy stage is a top-level declarative stage so Restart from Stage is available.
- Pass the image tag through
envcomputed from the commit (deterministic), not from a stash. - Add automatic retry only for infrastructure errors around the API calls:
retry(count: 2, conditions: [kubernetesAgent(), nonresumable()]), plus aretry(2)aroundkubectl applywith backoff. - Enable
preserveStashes(buildCount: 5)if the stage needs stashed manifests.
Why โ Restart from Stage reuses earlier stage results and redeploys the exact same artifact.
Interview tip โ Connect to "build once, deploy many".
Q5 A pipeline must run integration tests against a shared staging database that can only handle one test run at a time across four different repos. How do you coordinate?
Intermediate
Situation read โ disableConcurrentBuilds only works per job; we need a cross-job mutex.
What I'd do โ
- Install Lockable Resources and define a resource
staging-db(via JCasC underunclassified.lockableResourcesManager). - Wrap only the integration stage:
stage('Integration') { options { lock(resource: 'staging-db') } steps { sh './run-it.sh' } } - Put a
timeouton the stage so a hung test releases the lock. - Long term, give each run an ephemeral database (a Testcontainers Postgres in the pod) and remove the lock.
Why โ lock queues builds across jobs and releases automatically when the block exits, even on failure.
Interview tip โ Say that locks hide a scalability problem; ephemeral environments are the real fix.
Q6 A library must be tested on Node 18, 20 and 22, on Linux and Windows, but Node 18 on Windows is not supported. Design the stage.
Intermediate
Situation read โ Classic matrix with an exclusion.
What I'd do โ
stage('Test') {
matrix {
axes {
axis { name 'NODE_VERSION'; values '18', '20', '22' }
axis { name 'PLATFORM'; values 'linux', 'windows' }
}
excludes {
exclude {
axis { name 'NODE_VERSION'; values '18' }
axis { name 'PLATFORM'; values 'windows' }
}
}
agent { label "${PLATFORM}" }
stages { stage('npm test') { steps { script {
if (isUnix()) { sh 'npm ci && npm test' } else { bat 'npm ci && npm test' }
} } } }
}
}- Select Node per cell with nvm/fnm or a container image tag per version on Linux.
- Publish JUnit per cell so failures show which combination broke.
Why โ matrix generates five parallel cells with readable names and no copy-pasted stages.
Interview tip โ Mention isUnix() for cross-platform steps.
Q7 Your 700-line Jenkinsfile now fails with Method code too large!. You need a fix today and a plan for next month.
Advanced
Method code too large!. You need a fix today and a plan for next month.Situation read โ The compiled pipeline exceeds the JVM's 64 KB method limit.
What I'd do โ
- Today: move the longest inline
sh '''...'''blocks into script files in the repo (ci/deploy.sh), which shrinks bytecode dramatically. - Try enabling script splitting via the system property
-Dorg.jenkinsci.plugins.pipeline.modeldefinition.parser.RuntimeASTTransformer.SCRIPT_SPLITTING_TRANSFORMATION=true. - Next month: extract repeated stage logic into shared library steps, replace copy-pasted per-environment stages with a loop or
matrix, and split release and CI into separate jobs.
Why โ The limit is on generated bytecode, so less inline code and fewer stages per method are the only real fixes.
Interview tip โ Use this to show you know the Jenkinsfile is compiled Groovy, not YAML.
Q8 A nightly job should run only on main in a multibranch project, but every feature branch also fires at 2 AM. What is wrong and how do you fix it?
Intermediate
main in a multibranch project, but every feature branch also fires at 2 AM. What is wrong and how do you fix it?Situation read โ triggers { cron('H 2 * * *') } in the Jenkinsfile registers the trigger on every branch job that has the file.
What I'd do โ
- Make the cron conditional:
triggers { cron(env.BRANCH_NAME == 'main' ? 'H 2 * * *' : '') } - Note that the trigger registers after the next build of each branch, so trigger one build per branch or wait for the next push.
- Alternatively, move nightly work to a separate pipeline job targeting
main.
Why โ Triggers are job properties set by running the Jenkinsfile; an empty cron string clears them.
Interview tip โ Mention that properties in a Jenkinsfile only apply after the build runs once.
Q9 Product asks for a "deploy any version to any environment" button. How do you design the job?
Intermediate
Situation read โ Separate the promotion/deploy job from the CI pipeline, deploying existing artifacts only.
What I'd do โ
- Create a parameterized pipeline
deploy/shack-appwithchoice(name: 'ENV', choices: ['dev','staging','prod'])andstring(name: 'TAG'). - Validate the tag exists in the registry (
crane digest $IMAGE:$TAG) and was built frommain. - Gate prod with a stage
inputrestricted torelease-managers, and use folder permissions so only certain groups can build the job. - Record
currentBuild.displayName = "${params.ENV} ${params.TAG}"for an audit-friendly history.
Why โ Deploying artifacts by tag never rebuilds and gives a clear deployment log per environment.
Interview tip โ Say that with GitOps, this job would open a PR to the config repo instead of calling kubectl.
Q10 A stage should run only when files under infra/ changed, but on new branches it never runs. Why, and what do you do?
Advanced
infra/ changed, but on new branches it never runs. Why, and what do you do?Situation read โ when { changeset 'infra/**' } compares against changes since the previous build of that branch job. The first build of a new branch has no recorded changesets, so the condition is false.
What I'd do โ
- Compute the diff against the target branch yourself:
when { expression { sh(script: 'git diff --name-only origin/main...HEAD | grep -q "^infra/"', returnStatus: true) == 0 } } - Ensure the clone fetches
main(not a shallow single-branch clone). - For PRs, use
CHANGE_TARGETinstead of hardcodingmain.
Why โ Diffing against the merge base is deterministic regardless of build history.
Interview tip โ Knowing the first-build changeset gotcha signals real Jenkins experience.
Q11 A team insists on scripted pipelines because "declarative is too restrictive". How do you respond?
Beginner
Situation read โ Usually they hit one limitation (dynamic stages, complex conditions) and abandoned declarative entirely.
What I'd do โ
- Ask for the concrete limitation; most are solved with
script {},matrix,when { expression {} }or a library step. - Show dynamic
parallelinside ascriptblock for runtime-generated stages. - Point out what they lose with scripted: syntax validation, Restart from Stage,
postconditions, consistent UI. - Agree on a rule: declarative skeleton, scripted logic only in reviewed library steps.
Why โ Consistency across hundreds of repos matters more than per-team freedom.
Interview tip โ Frame it as a standard with escape hatches, not a ban.
Q12 Builds are green even though the test step printed failures, because the test command's exit code is swallowed by a pipe. How do you make the pipeline honest?
Beginner
Situation read โ sh 'npm test | tee test.log' returns the exit code of tee, not npm test.
What I'd do โ
- Use
set -o pipefailwith bash:sh '''#!/bin/bash set -euo pipefail npm test | tee test.log ''' - Publish JUnit results with
allowEmptyResults: false, so missing reports also fail. - Review other
shsteps for|| trueand pipes.
Why โ /bin/sh on many images is dash, which lacks pipefail; the shebang forces bash.
Interview tip โ Mention both the shell issue and making test reports the source of truth.
Q13 You need the build to be UNSTABLE when coverage drops below 80% but still produce an artifact. How?
Beginner
Situation read โ A soft gate: visible signal, no blocked delivery for this branch.
What I'd do โ
- Parse coverage in a step and call
unstable:script { def pct = sh(script: "jq '.total.lines.pct' coverage/coverage-summary.json", returnStdout: true).trim() as Double if (pct < 80) { unstable("Line coverage ${pct}% is below 80%") } } - Or use the Coverage plugin's
recordCoveragewith quality gates set to unstable. - Make
maindeploy stages requirecurrentBuild.currentResult == 'SUCCESS'if unstable builds must not ship.
Why โ UNSTABLE is Jenkins' built-in "passed with warnings" state.
Interview tip โ Explain the difference between result and currentResult.
Q14 Your pipeline uses stash to move a 3 GB build output between stages on different agents and the controller struggles. What do you change?
Intermediate
stash to move a 3 GB build output between stages on different agents and the controller struggles. What do you change?Situation read โ Stashes are tarred through the controller and stored in JENKINS_HOME.
What I'd do โ
- Keep stages that need the output on one agent (nested stages under one parent
agent). - If you must cross agents, push to an artifact store (Nexus raw repo, S3) and pull by build ID.
- Install Artifact Manager on S3 so stash and archive go directly from agent to S3.
- Stash only what is needed (
includes: 'dist/**'), not the whole workspace.
Why โ The controller is a scheduler, not a file server; large stashes cause heap and disk pressure.
Interview tip โ Say "stash for kilobytes to a few MB, artifact store for anything big".
Q15 A release pipeline needs two approvals: QA lead, then a release manager, each from a different group. How do you model it?
Intermediate
Situation read โ Sequential gates with different submitters and audit.
What I'd do โ
- Two stages with stage-level
inputand no agent:stage('QA sign-off') { options { timeout(time: 1, unit: 'DAYS') } input { message 'QA approved?'; submitter 'qa-leads'; submitterParameter 'QA_APPROVER' } steps { echo "QA: ${QA_APPROVER}" } } stage('Release approval') { options { timeout(time: 1, unit: 'DAYS') } input { message 'Release to prod?'; submitter 'release-managers'; submitterParameter 'RM_APPROVER' } steps { echo "RM: ${RM_APPROVER}" } } - Write approver names into
currentBuild.descriptionand the change ticket. - Ensure the same person cannot approve both (check
QA_APPROVER != RM_APPROVERand fail).
Why โ Group-restricted submitters plus recorded identities give separation of duties.
Interview tip โ Mention that admins can always approve, so keep the admin group small.
Q16 Some tests are flaky and fail one build in ten. Product wants green builds now. What do you do in Jenkins, and what do you refuse to do?
Intermediate
Situation read โ Retrying the whole stage hides real failures; we need targeted mitigation and tracking.
What I'd do โ
- Retry at the test-framework level for known flaky tests only (
jest --retryTimesscoped by tag, Maven SurefirererunFailingTestsCount=2); Surefire reports flakes in XML. - Track flaky tests with JUnit history and quarantine them into a separate non-blocking stage using
catchError(buildResult: 'SUCCESS', stageResult: 'UNSTABLE'). - Use
retrywithconditions: [agent(), kubernetesAgent()]only for infra failures. - Refuse a blanket
retry(3)around the test stage.
Why โ Blind retries turn real intermittent bugs into invisible production incidents.
Interview tip โ Separate infra flakiness (retry) from test flakiness (fix or quarantine).
Q17 A Jenkinsfile must work for both PR builds (no push, no deploy) and main builds (push and deploy). Show the structure.
Beginner
main builds (push and deploy). Show the structure.Situation read โ One file, branch-aware stages.
What I'd do โ
stage('Push image') {
when { branch 'main' }
steps { pushImage() }
}
stage('Deploy dev') {
when { allOf { branch 'main'; not { changeRequest() } } }
steps { deploy('dev') }
}- All PR builds run build, test, scan.
- Push and deploy stages run only on
main. - Deploy credentials are scoped so PR jobs cannot use them even if someone edits the
when.
Why โ One Jenkinsfile avoids drift between PR and main pipelines.
Interview tip โ Always pair when conditions with credential scoping; when alone is not a security control.
Q18 Your pipeline should automatically roll back the Kubernetes deployment if the post-deploy smoke test fails. Design it.
Intermediate
Situation read โ Deploy, verify, and undo on failure within the same stage.
What I'd do โ
stage('Deploy prod') {
steps {
container('kubectl') {
sh 'kubectl -n shack-prod set image deploy/shack-app app=$IMAGE:$TAG'
sh 'kubectl -n shack-prod rollout status deploy/shack-app --timeout=180s'
sh './ci/smoke.sh https://shack.example.com'
}
}
post {
failure { container('kubectl') { sh 'kubectl -n shack-prod rollout undo deploy/shack-app' } }
}
}- Annotate the change cause (
kubernetes.io/change-cause) with the build URL. - Alert the channel on rollback.
Why โ rollout status catches failed pods, the smoke test catches broken behaviour, and post failure handles both.
Interview tip โ Mention progressive delivery (Argo Rollouts) as the next step beyond scripted rollback.
Q19 Two teams copy the same 150-line Jenkinsfile with small differences. Each fix must be applied in 40 repos. What do you propose?
Intermediate
Situation read โ Classic case for a shared library.
What I'd do โ
- Identify the common steps (build, test, scan, push, deploy) and create library steps with sane defaults.
- Offer a pipeline template step (
nodeServicePipeline(...)) for standard services, plus building blocks for special ones. - Version the library (
v1), migrate repos with automated PRs, and keep each Jenkinsfile under 20 lines. - Track adoption by logging library version per build.
Why โ One fix lands everywhere when the moving tag is updated, with a controlled rollout.
Interview tip โ Mention the trade-off: templates limit flexibility, so leave extension hooks.
Q20 A pipeline runs a 3-hour performance test. If the controller restarts mid-run, the build is lost. How do you make long builds resilient?
Advanced
Situation read โ Durability, agent survival and step design all matter.
What I'd do โ
- Use
durabilityHint('MAX_SURVIVABILITY')for this pipeline. - Run the test on a static agent or a pod that survives controller restarts (pods are not deleted when the controller restarts; they reconnect if the controller returns within the agent's timeout).
- Use plain
shsteps (durable tasks) which keep running and writing output to the agent during the restart. - Do maintenance with quiet-down so new long builds do not start before a planned restart.
- Better: trigger the perf test in an external system and have Jenkins wait on it, so Jenkins restarts do not matter.
Why โ Pipeline resume needs persisted CPS state plus a surviving agent and a durable step.
Interview tip โ Explain that sh is durable because output goes to files on the agent, not the channel.
Shared libraries & multibranch
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q21 A shared library change merged to main broke 200 pipelines within minutes. How do you prevent a repeat?
Intermediate
main broke 200 pipelines within minutes. How do you prevent a repeat?Situation read โ Pipelines loaded the library's default version main, so every merge was an instant global rollout.
What I'd do โ
- Set the global library's default version to a tag (
v1), and have Jenkinsfiles pin@Library('shack-lib@v1'). - Release flow: PR with JenkinsPipelineUnit tests, merge, tag
v1.7.0, run a canary set of pipelines on a staging controller, then move thev1tag. - Disable "Allow default version to be overridden" on production, or provide a separate
shack-lib-devconfig for testing branches. - Roll back by moving
v1back to the previous tag.
Why โ Tags turn library releases into deliberate, reversible events.
Interview tip โ Say "the library is production code that runs unsandboxed, so it gets a release process".
Q22 You want to test a library branch against a real app pipeline without affecting anyone. How?
Beginner
Situation read โ Need an isolated way to load an unreleased library version.
What I'd do โ
- On a staging controller or in a test folder, define a folder-level library
shack-libpointing to the same repo with version override allowed. - Use Replay on a recent app build and change the annotation to
@Library('shack-lib@feature/kaniko-cache') _. - Or create a test branch of the app repo with that annotation.
- Run JenkinsPipelineUnit tests in the library's own CI first.
Why โ Folder-level libraries are sandboxed and scoped, so experiments cannot leak into production pipelines.
Interview tip โ Mention Replay as the fastest feedback loop.
Q23 Every app repo has its own pod YAML for builds, and they all drift. How do you standardize?
Intermediate
Situation read โ Pod templates are platform concerns and belong in the library or cloud config.
What I'd do โ
- Put standard pod definitions in
resources/pods/node.yaml,maven.yamlin the shared library. - Expose a step that wraps them:
// vars/withBuildPod.groovy def call(String type, Closure body) { podTemplate(yaml: libraryResource("pods/${type}.yaml")) { node(POD_LABEL) { body() } } } - Or define named templates in JCasC with a common base (
inheritFrom) and let apps reference labels. - Allow overrides via a merge (
yamlMergeStrategy: merge()) for resources only.
Why โ One place to update images, security contexts and resource requests.
Interview tip โ Mention that image bumps then happen via library releases, not 100 PRs.
Q24 Security wants every pipeline to run a secret scan, even if teams forget to add it. How?
Advanced
Situation read โ Enforcement must not rely on each Jenkinsfile.
What I'd do โ
- Make the standard pipeline template include the scan; teams using the template get it automatically.
- For custom pipelines, use an implicitly loaded library with a
vars/step called from the template, or enforce at org folder level with the Pipeline: Multibranch with defaults or Templating Engine (JTE) approach where the pipeline skeleton is defined centrally. - Add a branch protection required check that comes from a separate, centrally owned job (
security/secret-scan), not from the team's Jenkinsfile. - Report pipelines missing the stage via build metadata.
Why โ A required check produced outside the team's control cannot be removed by editing their Jenkinsfile.
Interview tip โ Name the Jenkins Templating Engine as the "governance" option.
Q25 A multibranch project has 600 stale branch jobs and the folder page takes 30 seconds to load. What do you do?
Beginner
Situation read โ Orphaned branches are kept forever, and old builds are not discarded.
What I'd do โ
- Set the orphaned item strategy to discard old items: days to keep 7, max 20.
- Add
buildDiscarder(logRotator(numToKeepStr: '10'))in the Jenkinsfile. - Filter discovery to relevant heads (
main,release/*, PRs) with a wildcard filter. - Run Scan Repository Now to apply the cleanup.
Why โ Each job and build directory is loaded into memory; fewer items means faster UI and smaller heap.
Interview tip โ Mention coordinating with teams before deleting release branch history.
Q26 A new org with 150 repositories wants Jenkins builds for every repo with a Jenkinsfile, without tickets to the platform team. What do you set up?
Intermediate
Situation read โ Organization folder use case.
What I'd do โ
- Create a GitHub Organization folder with a GitHub App credential, defined in JCasC/Job DSL (
organizationFolder('acme') { organizations { github { repoOwner('acme') ... } } }). - Discover repos with a
Jenkinsfile, branches excluding PR branches, PRs merged with target, forks trusted only from collaborators. - Configure an org-level webhook to
/github-webhook/. - Apply folder-level credentials and permissions for the org.
- Set orphaned item strategy and a periodic scan (1 day) as backup.
Why โ New repos are picked up automatically and builds start on the first push.
Interview tip โ Mention GitHub App rate limits as the reason not to use a personal token at this scale.
Q27 PRs from forks must be built, but the security team is worried about secrets. How do you configure it?
Advanced
Situation read โ Fork PRs run untrusted code; the Jenkinsfile and build scripts can be attacker-controlled.
What I'd do โ
- Set fork PR trust to "From users with Admin or Write permission" (or Nobody), so untrusted forks run the target branch's Jenkinsfile.
- Remember the target Jenkinsfile still runs the fork's code (tests, build scripts), so do not bind any secrets in PR stages.
- Run PR builds on a separate, isolated agent pool (different namespace or cluster, no network to internal systems).
- Require a maintainer comment or label to trigger builds for first-time contributors.
Why โ Trust settings protect the pipeline definition, not the code it executes; isolation protects the rest.
Interview tip โ This "trusted Jenkinsfile, untrusted code" distinction is what interviewers want to hear.
Q28 You need a release pipeline that runs when a tag like v1.4.0 is pushed. Tag jobs appear in multibranch but never build. Make it work.
Intermediate
v1.4.0 is pushed. Tag jobs appear in multibranch but never build. Make it work.Situation read โ Tags are discovered but not built automatically by default.
What I'd do โ
- Add the "Discover tags" trait.
- Install Basic Branch Build Strategies and add "Tags" with "Ignore tags older than 1 day" plus "Regular branches" and "Change requests" (adding any strategy replaces the default, so list all you need).
- In the Jenkinsfile, gate release stages with
when { buildingTag() }orwhen { tag pattern: 'v\\d+\\.\\d+\\.\\d+', comparator: 'REGEXP' }. - Use
TAG_NAMEas the version.
Why โ The age limit prevents a flood of builds for historical tags on first indexing.
Interview tip โ Mention that adding build strategies overrides the defaults, a common trap.
Q29 A library step needs a 200-line bash script, and escaping it inside Groovy strings is causing bugs. How do you structure it?
Beginner
Situation read โ Groovy string escaping ($, \, quotes) is error-prone.
What I'd do โ
- Put the script in
resources/scripts/deploy.shin the library. - Load and run it:
writeFile file: '.ci/deploy.sh', text: libraryResource('scripts/deploy.sh') sh 'bash .ci/deploy.sh' - Pass inputs as environment variables with
withEnv, not interpolation. - Lint the script with ShellCheck in the library's CI.
Why โ The script stays a real shell file: testable, lintable, no Groovy escaping.
Interview tip โ Mention injection safety as a bonus of env-var passing.
Q30 A team's multibranch job builds every push to every branch, including dependabot/* branches that also have PRs. Builds double. Fix.
Beginner
dependabot/* branches that also have PRs. Builds double. Fix.Situation read โ Branch discovery is set to "All branches".
What I'd do โ
- Set branch discovery to "Exclude branches that are also filed as PRs".
- Keep PR discovery with "merge with target".
- Optionally filter out
dependabot/*branch builds with a name filter and rely on their PR builds.
Why โ Each change is built once in the form that matters (the PR merge result).
Interview tip โ Explain why merge strategy tests what will land on main.
Q31 How would you add a common post-build step (send build metrics) to every pipeline on the controller?
Advanced
Situation read โ Cross-cutting concern; editing every Jenkinsfile does not scale.
What I'd do โ
- Prefer platform-level collection: the OpenTelemetry or Prometheus plugin captures build durations and results for all jobs without pipeline changes.
- For custom data, add it to the shared pipeline template's
post { always { } }. - For pipelines not using the template, an implicitly loaded library step can be called from a pipeline-level hook only if included, so combine with adoption tracking.
Why โ Plugins observe all builds centrally; templates add custom logic where needed.
Interview tip โ Mention OpenTelemetry tracing pipelines in Jaeger or Grafana Tempo.
Q32 A library uses a class that stores the build's config in a static field. Builds started at the same time see each other's values. Why and how do you fix it?
Advanced
Situation read โ Library classes are loaded once per library version per controller classloader context and static fields are shared across concurrent builds.
What I'd do โ
- Remove static mutable state; pass config as method arguments or instance fields.
- Create instances per build (
new Config(this, params)) and keep themSerializable. - Add a JenkinsPipelineUnit test that simulates two configs.
Why โ Static fields behave like global variables across builds, and CPS resume makes them even less predictable.
Interview tip โ Say "library code must be stateless across builds".
Q33 You must migrate 80 Freestyle jobs to multibranch pipelines. Plan it.
Intermediate
Situation read โ Large migration; reduce risk and repetition.
What I'd do โ
- Inventory jobs with the API (
/api/json?tree=jobs[name,_class]) and group by pattern (Maven app, Node app, cron script). - Build library steps or templates for each pattern.
- Add Jenkinsfiles via automated PRs, generating the parameters from each job's
config.xml. - Create multibranch jobs via Job DSL in JCasC; run both old and new in parallel for a week, comparing results.
- Disable Freestyle jobs, then delete after a retention period.
Why โ Pattern-based templates make the 80 jobs mostly mechanical, and parallel running catches gaps.
Interview tip โ Mention the cron/admin jobs might stay as simple pipelines, not every job needs multibranch.
Q34 A global library is configured as "Load implicitly", and a developer asks why their pipeline got a new behaviour without any change on their side. How do you handle it?
Beginner
Situation read โ Implicit libraries load the default version into every pipeline automatically.
What I'd do โ
- Explain the implicit load and show the build log line
Loading library shack-lib@v1. - Check the library changelog between the last good and current builds.
- Advise pinning a specific tag in their Jenkinsfile if they need stability (
@Library('[email protected]') _). - Review whether implicit loading is justified; restrict it to small, stable utilities.
Why โ Implicit loading trades explicitness for convenience; teams must know it exists.
Interview tip โ Recommend explicit @Library in all pipelines for readability.
Q35 You want branch builds and PR builds to report separate statuses to GitHub and block merges when either fails. Configure it.
Intermediate
Situation read โ GitHub branch protection needs the right context names.
What I'd do โ
- Note Jenkins contexts:
continuous-integration/jenkins/branchandcontinuous-integration/jenkins/pr-merge. - In branch protection for
main, requirecontinuous-integration/jenkins/pr-merge(PRs are what merge). - Use the GitHub Checks plugin with a GitHub App to publish per-stage checks if you want "SonarQube" and "Trivy" as separate required checks via
publishChecks. - Verify the credential can write statuses.
Why โ Requiring the PR-merge context guarantees the merged result was built.
Interview tip โ Mention that status names must match exactly or the PR waits forever.
Q36 A team needs the same pipeline for 25 microservices in one monorepo, but only changed services should build. Design it in Jenkins.
Advanced
Situation read โ One multibranch job, dynamic stages based on the diff.
What I'd do โ
- Compute changed services:
def base = env.CHANGE_TARGET ? "origin/${env.CHANGE_TARGET}" : 'HEAD~1' def changed = sh(script: "git diff --name-only ${base}...HEAD | cut -d/ -f2 | sort -u", returnStdout: true).trim().split('\n') - Build a
parallelmap with one branch per changed service, each calling a library step. - Force all services to build on
mainnightly or when shared code (libs/) changes. - Cache dependencies per service via a repository manager.
Why โ Dynamic parallel keeps one pipeline while avoiding 25 full builds per commit.
Interview tip โ Mention that for very large monorepos a graph-aware build tool beats shell diffs.
Q37 You need to share configuration (registry URL, Sonar server name, cluster names) across all pipelines without hardcoding. Where do you put it?
Intermediate
Situation read โ Non-secret global settings.
What I'd do โ
- Global environment variables set via JCasC (
jenkins.globalNodeProperties.envVars), or folder-level properties for per-team values. - Or a library
resources/config/defaults.yamlread viareadYaml text: libraryResource(...). - Keep secrets in credentials, never in these.
Why โ Values change in one place and are versioned with the platform code.
Interview tip โ Folder properties allow team-specific overrides with the same variable names.
Q38 A team asks to write a vars/ step that calls Jenkins internal APIs (Jenkins.instance.getItem) to list jobs. Should it live in the trusted library?
Advanced
vars/ step that calls Jenkins internal APIs (Jenkins.instance.getItem) to list jobs. Should it live in the trusted library?Situation read โ Trusted library code runs unsandboxed; any step there becomes a capability every pipeline gets.
What I'd do โ
- Ask what the real need is; often the REST API or a plugin step answers it.
- If needed, implement a narrow step (
listJobsInFolder(folder)) that returns names only, validates input, and checks the caller's folder. - Review it like privileged code; never expose generic "run this Groovy" helpers.
- Prefer doing such admin tasks in a separate admin-only job.
Why โ A trusted library is an admin API surface for all Jenkinsfile authors.
Interview tip โ Tie it to the principle of least privilege.
Platform: plugins, JCasC & Kubernetes agents
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q39 You inherit a controller with 230 plugins, half unused, on a version two LTS lines behind. Plan the cleanup and upgrade.
Advanced
Situation read โ Large surface, upgrade risk compounds with plugin count.
What I'd do โ
- Export the plugin list and current config (
/configuration-as-code/viewExport), back upJENKINS_HOME. - Find usage with the Plugin Usage plugin and by grepping
jobs/*/config.xmland Jenkinsfiles for steps; mark unused plugins (dependencies of used ones stay). - Clone production to staging, remove unused plugins there, check for "old data" and broken jobs.
- Build an image with the target LTS and
jenkins-plugin-cli --jenkins-version <target> --available-updates. - Upgrade staging, run smoke pipelines, then production with quiet-down and a rollback image.
- Move everything into
plugins.txtand JCasC so this never accumulates again.
Why โ Removing plugins before upgrading reduces conflicts and testing scope.
Interview tip โ Mention the Java 17 requirement as a classic upgrade blocker.
Q40 An admin changes a cloud setting in the UI, and it reverts after the next controller restart. Developers are confused. What is your policy?
Beginner
Situation read โ JCasC owns that section and reapplies it at startup.
What I'd do โ
- Explain JCasC as the source of truth and make the change via PR to
jenkins.yaml. - Add a system message: "Configured by JCasC, UI changes will be lost".
- Restrict
Overall/Administerto the platform team. - Use the JCasC export to diff UI state against Git periodically.
Why โ Mixed ownership leads to silent reverts and outages.
Interview tip โ Say "the UI is read-only for configuration on our controllers".
Q41 You must stand up a new Jenkins controller for a team in under an hour, identical to the existing ones. How?
Intermediate
Situation read โ Needs image + JCasC + Job DSL + secrets.
What I'd do โ
- Reuse the platform controller image (pinned core and plugins).
- Create a values/overlay file for the team: URL, SSO group mapping, folder names, credentials references.
helm upgrade --install jenkins-payments jenkins/jenkins -f base.yaml -f payments.yaml -n jenkins-payments.- Job DSL in JCasC creates the team's org folder; indexing creates all jobs.
- Verify with a smoke pipeline.
Why โ Everything is parameterized code, so a controller is a deployment, not a project.
Interview tip โ Mention the same mechanism doubles as disaster recovery.
Q42 Builds wait 2โ3 minutes before starting because new agent pods are slow to schedule. How do you speed up agent startup?
Advanced
Situation read โ Time goes into node scale-up, image pulls and the agent connecting.
What I'd do โ
- Check pod events:
kubectl -n jenkins-agents describe pod <pod>forPulling imageduration andFailedScheduling. - Use smaller, pinned images and pre-pull them on build nodes (a DaemonSet that pulls them, or node image baking).
- Keep a small warm buffer: overprovisioning pause pods with low priority so the autoscaler keeps spare nodes.
- Set
imagePullPolicy: IfNotPresentwith immutable tags. - Consider
idleMinutesfor very frequent short jobs.
Why โ Pod startup is mostly image pulls and node provisioning, both fixable at the cluster level.
Interview tip โ Quote the breakdown: scheduling, pull, container start, agent connect.
Q43 Developers need Docker image builds in Kubernetes agents, but the cluster runs containerd and security forbids privileged pods. What do you choose?
Advanced
Situation read โ No Docker socket, no privileged containers.
What I'd do โ
- Evaluate Kaniko (runs as root inside the container but not privileged) or BuildKit rootless (needs
seccomp/apparmorunconfined but not privileged). - Run builders on a dedicated tainted node pool with no access to production networks.
- Push to the registry with short-lived credentials; use a registry cache repo for layer caching.
- If policy forbids root entirely, use a remote BuildKit service run by the platform team or a managed builder.
Why โ Daemonless builders avoid the host socket and fit containerd clusters, with isolation compensating for their remaining privileges.
Interview tip โ Mention Kaniko's archived upstream status and that you would track a maintained fork or BuildKit.
Q44 The controller needs to provision agents in three Kubernetes clusters in different regions. How do you configure it?
Advanced
Situation read โ Multiple clouds in the kubernetes plugin, external API access.
What I'd do โ
- Define three
kubernetesclouds in JCasC, each withserverUrl,serverCertificate,namespaceand a credential (service account token or kubeconfig as a Secret file credential). - Set
jenkinsUrlto the public HTTPS URL andwebSocket: trueso remote pods connect through the ingress. - Give each cloud distinct pod template labels (
k8s-eu,k8s-us) and set capacity limits. - Create RBAC in each cluster for the Jenkins service account in the agents namespace.
Why โ WebSocket over HTTPS avoids exposing TCP 50000 across regions.
Interview tip โ Mention that one controller across regions still has one point of failure; consider regional controllers.
Q45 You want to roll out a new version of the jnlp inbound-agent image to all pod templates. How?
Beginner
jnlp inbound-agent image to all pod templates. How?Situation read โ The jnlp image is set per template or defaulted by the plugin.
What I'd do โ
- Define the
jnlpcontainer once in a base template in JCasC (name: base, containerjnlpwithimage: jenkins/inbound-agent:<version>-jdk21). - Make other templates
inheritFrom: base. - Bump the version in JCasC via PR, reload, run smoke builds.
Why โ Inheritance means one change propagates; agents with old remoting versions can also trigger compatibility warnings.
Interview tip โ Keep the remoting version close to the controller's for compatibility.
Q46 A Job DSL seed in JCasC should create a folder per team from a YAML list. How do you structure it?
Intermediate
Situation read โ Data-driven job generation.
What I'd do โ
- Store
teams.yamlin the platform repo, mounted into the controller. - Job DSL script:(When run from JCasC, read the file with plain Groovy
def teams = new org.yaml.snakeyaml.Yaml().load(readFileFromWorkspace('teams.yaml')) teams.each { t -> folder(t.name) { displayName(t.display) } organizationFolder("${t.name}/repos") { /* github org config */ } }new File('/var/jenkins_config/teams.yaml').text.) - Apply folder permissions and credentials per team in the same script.
Why โ Adding a team is a one-line YAML change reviewed in Git.
Interview tip โ Mention Job DSL's removedJobAction for cleaning up deleted teams.
Q47 How do you prevent one team's builds from using all agent capacity in a shared Kubernetes cluster?
Intermediate
Situation read โ Fairness and isolation across teams.
What I'd do โ
- Separate agent namespaces per team with
ResourceQuotaandLimitRange. - A kubernetes cloud per namespace (or per team controller) with its own concurrency limit.
- Enforce resource requests in pod templates so scheduling is predictable.
- Monitor queue time per team.
Why โ Quotas cap usage at the cluster level, regardless of what Jenkins requests.
Interview tip โ Mention priority classes for release builds over PR builds.
Q48 Your controller runs on Kubernetes. A node drain for an upgrade kills the controller pod mid-day. How do you make maintenance safe?
Advanced
Situation read โ Single-replica StatefulSet is disrupted by drains.
What I'd do โ
- Add a PodDisruptionBudget with
maxUnavailable: 0so drains block until an operator acts. - Schedule maintenance windows: quiet-down via API, wait for builds, then drain.
- Set a long
terminationGracePeriodSecondsand apreStophook that calls/safeExitif desired. - Put the controller on a dedicated node pool upgraded separately.
Why โ The controller is a stateful singleton; it needs explicit handling during cluster operations.
Interview tip โ Mention that build pods also need PDB thinking or tolerance to eviction.
Q49 A plugin you rely on has been abandoned and has an unfixed security advisory. What are your options?
Intermediate
Situation read โ Risk accepted, mitigated or removed.
What I'd do โ
- Read the advisory: what permission is needed to exploit it? Maybe only admins can trigger it.
- Look for a replacement plugin or replace with
shsteps calling a CLI. - If it must stay short term, reduce exposure (restrict permissions, disable affected features) and document the risk acceptance with an expiry.
- Consider adopting the plugin (the Jenkins project has an "adopt a plugin" process).
Why โ Abandoned plugins only get worse with every core upgrade.
Interview tip โ Prefer CLI tools in containers over niche plugins in general.
Q50 A team needs GPU agents only for model training jobs, which run twice a week. How do you provide them?
Intermediate
Situation read โ Expensive, rare resource; must not idle.
What I'd do โ
- A pod template labelled
gpuwithnodeSelectorfor the GPU node pool,tolerationsfor its taint, andresources.limits: nvidia.com/gpu: 1. - Cluster autoscaler scales the GPU pool from zero when a pod is pending.
- Restrict the template to the ML folder (separate cloud with folder restriction or Job Restrictions).
- Set a pipeline timeout so jobs do not hold GPUs indefinitely.
Why โ Ephemeral pods on scale-to-zero nodes mean GPUs cost money only during training.
Interview tip โ Mention instanceCap to limit concurrent GPU pods.
Q51 You want every controller config change reviewed, but people still need to test changes quickly. Design the workflow.
Advanced
Situation read โ GitOps for Jenkins itself.
What I'd do โ
- Platform repo with
Dockerfile,plugins.txt,casc/*.yaml,jobs/*.groovy. - PR pipeline: build the image, start it in a container with test secrets, fail on
ConfiguratorExceptionin logs, run a smoke Jenkinsfile through the API. - Ephemeral preview controller per PR in a sandbox namespace for manual checks.
- Merge deploys to staging, then production via Helm with an approval.
Why โ Fast feedback plus review without anyone touching production UI.
Interview tip โ "We test Jenkins with Jenkins" usually lands well.
Q52 Pods for builds must pull images from a private registry. How do you configure it cleanly?
Intermediate
Situation read โ Kubernetes pull secrets for agent pods.
What I'd do โ
- Create a
docker-registrySecret in the agents namespace:kubectl -n jenkins-agents create secret docker-registry regcred \ --docker-server=registry.example.com --docker-username=ci --docker-password="$PASS" - Add
imagePullSecrets: [{name: regcred}]to the base pod template, or attach it to the agents' service account. - Prefer node-level registry auth (ECR credential helper, workload identity) in cloud clusters.
Why โ Pull secrets are a cluster concern; Jenkins credentials are not involved in image pulls.
Interview tip โ Distinguish pulling build images (cluster) from pushing built images (pipeline credentials).
Q53 Two plugins require different versions of a shared dependency, and jenkins-plugin-cli fails the image build. What do you do?
Intermediate
jenkins-plugin-cli fails the image build. What do you do?Situation read โ Dependency conflict, typically one plugin is too old for the other's requirement.
What I'd do โ
- Read the error; it names the plugin and required version.
- Update the older plugin to a version compatible with the newer dependency (check its changelog and required core).
- If one plugin is abandoned and blocks the upgrade, replace or remove it.
- Let
jenkins-plugin-cliresolve transitive dependencies; pin only top-level plugins plus any you explicitly need.
Why โ Over-pinning transitive dependencies causes many of these conflicts.
Interview tip โ Show you know the difference between top-level and transitive pins.
Q54 An auditor asks you to prove the Jenkins configuration in production equals what is in Git. How?
Intermediate
Situation read โ Drift detection.
What I'd do โ
- A scheduled job exports
/configuration-as-code/viewExport(admin token) and diffs it against the rendered YAML in Git, ignoring generated fields. - Compare installed plugins (
pluginManager/api/json) withplugins.txt. - Use Job Configuration History to show any UI changes with authors.
- Alert on drift and enforce read-only by restricting admin rights.
Why โ Continuous drift detection is the evidence auditors want.
Interview tip โ Mention the image digest in the running pod as evidence for core and plugin versions.
Q55 Builds in Kubernetes need a Maven cache, and downloads take 6 minutes per build. What do you implement?
Intermediate
Situation read โ Ephemeral pods start with an empty ~/.m2.
What I'd do โ
- Point Maven at a Nexus/Artifactory proxy inside the cluster via
settings.xmlmirror; this alone usually drops time to under a minute. - Optionally mount a shared PVC for
~/.m2/repository(ReadWriteMany), accepting concurrency risks, or a per-node cache. - Use
mvn -B -T 1Cand dependency:go-offline in a cached image layer for stable dependencies.
Why โ A nearby proxy turns internet downloads into LAN transfers and adds resilience.
Interview tip โ Mention that baking dependencies into the build image is another option for slow-changing deps.
Q56 Agents on Windows VMs must run alongside Kubernetes pods. How do you manage them as code?
Intermediate
Situation read โ Static agents need definitions and a connection method.
What I'd do โ
- Define the nodes in JCasC (
jenkins.nodes: - permanent: name, labelString, remoteFS, launcher: inbound with webSocket). - Install the agent as a Windows service using the Jenkins agent service wrapper (WinSW) with
-webSocketand the secret from a secure store. - Build the VM image with Packer (JDK 21, build tools) and replace VMs instead of patching.
- Label them
windows,EXCLUSIVEmode.
Why โ Both node definition and machine setup become reproducible.
Interview tip โ Mention the EC2 or Azure VM cloud plugins for ephemeral Windows agents.
Credentials & security
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q57 A security review finds AWS access keys stored as Jenkins credentials used by 60 pipelines. The goal is no long-lived keys. Plan it.
Advanced
Situation read โ Replace static keys with workload identity or short-lived tokens.
What I'd do โ
- For Kubernetes agents on EKS, use IRSA or EKS Pod Identity: deploy pod templates with a service account mapped to an IAM role; the AWS SDK picks up credentials automatically.
- For agents outside AWS, use OIDC federation (e.g. the controller issues tokens via a plugin) or Vault's AWS secrets engine issuing 15-minute credentials per build.
- Migrate pipelines folder by folder, then delete the keys and deactivate them in IAM.
- Scope roles per environment; prod role only usable by the prod deploy template.
Why โ Short-lived credentials limit blast radius when a build or log leaks them.
Interview tip โ Name IRSA/Pod Identity explicitly; it is the expected answer for EKS.
Q58 A developer printed a credential with echo $TOKEN | base64 and it appeared unmasked in the log. What do you do now and later?
Intermediate
echo $TOKEN | base64 and it appeared unmasked in the log. What do you do now and later?Situation read โ Masking only matches the exact value; the secret is exposed.
What I'd do โ
- Rotate the credential immediately; treat it as compromised.
- Delete the affected build logs (or the builds) and check who viewed them.
- Tighten who can modify pipelines that bind that credential: folder-scoped credentials, PR review for Jenkinsfiles, no Replay for non-admins.
- Add a log scan (e.g. gitleaks over archived logs) for leaked patterns.
Why โ Anyone who can run code with a secret can exfiltrate it; masking is not a control.
Interview tip โ Say "rotate first, investigate second".
Q59 Team A can see Team B's production kubeconfig in the credential dropdown. Fix the model.
Beginner
Situation read โ Credentials are global; access is not segmented.
What I'd do โ
- Create per-team folders and move each team's credentials into their folder's store.
- Grant
Credentials/ViewandJob/Configureonly within each team's folder (project matrix or role strategy). - Remove the global copies after migration.
Why โ Folder credentials are only resolvable by jobs inside the folder.
Interview tip โ Mention that Job/Configure in a folder implies use of its credentials.
Q60 Jenkins must be reachable by GitHub webhooks, but the UI must stay internal. Design the exposure.
Intermediate
Situation read โ Split public and private paths.
What I'd do โ
- Internal ingress/load balancer for the full UI, behind VPN or SSO proxy.
- A separate public ingress that routes only
/github-webhook/(and/sonarqube-webhook/if Sonar is external) to the Jenkins service; return 404 for everything else. - Restrict the public path to GitHub's hook IP ranges and require the webhook secret.
- Alternatively use a relay (a small service in a DMZ, or GitHub's webhook forwarding via a queue) so Jenkins has no inbound exposure.
Why โ Minimal public surface while keeping instant builds.
Interview tip โ Mention webhook HMAC verification as a second layer.
Q61 Your script approval list contains method hudson.model.Run getLog and staticMethod jenkins.model.Jenkins getInstance. What do you do?
Advanced
method hudson.model.Run getLog and staticMethod jenkins.model.Jenkins getInstance. What do you do?Situation read โ These approvals give every Jenkinsfile author access to Jenkins internals: Jenkins.getInstance leads to credentials and configuration.
What I'd do โ
- Find which pipelines use them (search Jenkinsfiles and recent
RejectedAccessExceptionhistory). - Replace with safe alternatives: library steps that do the specific job, or plugin steps.
- Revoke the dangerous approvals in
In-process Script Approval. - Audit recent builds for abuse; rotate high-value credentials if exploitation is plausible.
Why โ Approving internal API access effectively makes all pipeline authors admins.
Interview tip โ Demonstrate that you know which signatures are dangerous, not just "approve carefully".
Q62 A contractor needs to trigger and view builds for one project for three months. How do you grant access?
Beginner
Situation read โ Least privilege with an expiry.
What I'd do โ
- Add the contractor to an IdP group with an expiry date (e.g.
ext-shack-builders). - Grant that group
Overall/Readand on the project folderJob/Read,Job/Build,Job/Cancelonly. - No
Job/Configure,Run/Replayor credential permissions. - Review access at expiry.
Why โ Group-based grants in the IdP give central revocation and audit.
Interview tip โ Avoid local Jenkins users for humans.
Q63 You need to give a release bot a token to call the Jenkins API. How?
Beginner
Situation read โ Machine identity with minimal permissions.
What I'd do โ
- Create a service account user in the IdP or a local Jenkins user
svc-release-bot. - Grant only the permissions it needs on specific folders (
Job/Build,Job/Read). - Generate a named API token, store it in the bot's secret store, rotate periodically.
- Monitor token last-use and revoke unused ones.
Why โ Separate identity makes audit clear and limits damage if leaked.
Interview tip โ Mention that API tokens do not need CSRF crumbs.
Q64 A pentest shows Jenkins is behind a reverse proxy but the "It appears that your reverse proxy set up is broken" warning is shown and some redirects go to http://. What do you fix?
Intermediate
http://. What do you fix?Situation read โ The proxy does not forward the right headers, or the Jenkins URL is wrong.
What I'd do โ
- Set
unclassified.location.url: https://jenkins.example.com/in JCasC. - Configure the proxy to pass
Host,X-Forwarded-Proto: https,X-Forwarded-Port: 443andX-Forwarded-For, and to proxy WebSocket upgrades. - For nginx:
proxy_set_header X-Forwarded-Proto $scheme;andproxy_redirectcorrect; for ingress-nginx the defaults usually work with the URL set. - Enable HSTS at the proxy.
Why โ Jenkins builds absolute URLs from its configured URL and forwarded headers.
Interview tip โ Mention WebSocket agents also need upgrade headers through the proxy.
Q65 Jenkinsfiles in a repo deploy to production, and any developer with write access could edit the deploy stage in a branch. How do you prevent misuse?
Advanced
Situation read โ Pipeline code in a branch runs with whatever credentials it can reach.
What I'd do โ
- Prod credentials live in a separate folder used by a separate deploy job whose Jenkinsfile comes from a protected platform repo, not the app repo.
- The app pipeline only publishes an artifact and triggers the deploy job with the tag.
- The deploy job uses the Authorize Project plugin and an
inputrestricted to release managers. - Branch protection and CODEOWNERS on
Jenkinsfilechanges in app repos.
Why โ Separating "who writes the pipeline" from "who can deploy" is the only real fix.
Interview tip โ Or mention GitOps: Jenkins has no prod credentials at all.
Q66 You suspect a malicious build exfiltrated data. What Jenkins evidence do you gather?
Advanced
Situation read โ Incident response on CI.
What I'd do โ
- Preserve the build directory (
jobs/<job>/builds/<n>/): log,build.xml(cause, parameters), flow nodes. - Collect Audit Trail logs, Job Configuration History, and reverse proxy logs for the period.
- Check which credentials the job could bind and when the Jenkinsfile last changed (git history).
- Check agent pod/node logs and network egress logs (NetworkPolicy/firewall flow logs).
- Rotate every credential the job could access; restrict the job and review similar pipelines.
Why โ Jenkins data plus network logs reconstruct who ran what with which secrets.
Interview tip โ Mention egress restrictions on build agents as a preventive control.
Q67 A team wants to SSH into production servers from pipelines. How do you implement it safely?
Intermediate
Situation read โ SSH keys in CI are high value.
What I'd do โ
- Store the key as an SSH credential in the team's prod folder only.
- Use
sshagent(['prod-deploy-key']) { sh 'ssh -o StrictHostKeyChecking=yes deploy@host ...' }with known hosts pinned in the repo or image. - Limit the key on the server side (
command=inauthorized_keys, non-root user,from=agent IPs). - Prefer SSH certificates with short validity issued by Vault per build.
Why โ Narrow key capabilities and short lifetimes reduce impact of leaks.
Interview tip โ Never disable host key checking in pipelines.
Q68 Your org requires that only signed and scanned images reach production. Where does Jenkins fit?
Advanced
Situation read โ Jenkins produces evidence; the cluster enforces it.
What I'd do โ
- Pipeline: build to tarball, Trivy scan with gate, push, sign with cosign (keyless via OIDC or a KMS key), attach SBOM and scan attestations.
- Cluster: admission policy (Kyverno
verifyImagesor Sigstore policy-controller) that rejects unsigned or unattested images in prod namespaces. - Jenkins never holds a long-lived signing key in plain credentials; use KMS.
Why โ Enforcement at admission means bypassing Jenkins does not bypass the policy.
Interview tip โ "Jenkins signs, the cluster verifies".
Q69 A user reports they can see the whole job configuration including masked passwords in XML at /job/x/config.xml. Is this a leak?
Intermediate
/job/x/config.xml. Is this a leak?Situation read โ Users with Job/ExtendedRead or Job/Configure can read config.xml. Secrets in it are encrypted ({AQAAABAAAA...}), but anyone with script console access could decrypt them.
What I'd do โ
- Check who has
Job/Configure/ExtendedReadon that job. - Move secrets out of job parameters/configs into the credentials store and reference by ID.
- Use password parameters sparingly; they are stored encrypted but visible to configurers in encrypted form.
Why โ Encrypted-at-rest secrets are still only as safe as the admin boundary.
Interview tip โ Know that the {AQAAAB...} format is a Jenkins Secret.
Q70 You must enforce MFA for Jenkins access. How?
Beginner
Situation read โ Jenkins has no native MFA; delegate to the IdP.
What I'd do โ
- Configure the OpenID Connect or SAML security realm against Okta/Entra/Keycloak with MFA policies.
- Disable local accounts except one break-glass admin stored in a vault.
- API tokens remain for automation, tied to service users with minimal permissions.
Why โ SSO centralizes MFA, joiner/leaver processes and audit.
Interview tip โ Mention the break-glass account and testing it.
Q71 The security team wants all build agents to have no internet access except to approved registries. How do you implement it?
Advanced
Situation read โ Egress control for CI.
What I'd do โ
- Kubernetes NetworkPolicy in the agents namespace: default-deny egress, allow DNS, the Jenkins service, Nexus/Artifactory, the container registry and SonarQube.
- Route all dependency downloads through the repository manager (which has internet access and scans packages).
- For cloud APIs, use VPC endpoints.
- Monitor denied flows to find breakage.
Why โ Blocks exfiltration and dependency confusion attacks while keeping builds working.
Interview tip โ Mention that this also improves reproducibility because everything is proxied.
Q72 Somebody added Overall/Administer to the authenticated group "temporarily". How do you detect and prevent this?
Intermediate
Overall/Administer to the authenticated group "temporarily". How do you detect and prevent this?Situation read โ UI change to security config.
What I'd do โ
- Revert immediately via JCasC reload, which restores the defined authorization.
- Find the change in Audit Trail or Job Configuration History (system config).
- Make authorization JCasC-only and alert on drift.
- Reduce admins, require SSO+MFA.
Why โ Codified security config makes unauthorized changes temporary and visible.
Interview tip โ Mention periodic JCasC re-apply as a self-healing control.
Q73 Pipelines need database passwords at deploy time from AWS Secrets Manager. Compare two ways to integrate.
Advanced
Situation read โ Credentials provider vs runtime fetch.
What I'd do โ
- Credentials provider plugin: secrets tagged in Secrets Manager appear as Jenkins credentials; pipelines use
withCredentialsnormally; Jenkins needs IAM read on those secrets. - Runtime fetch: the deploy pod uses IRSA and runs
aws secretsmanager get-secret-value; Jenkins never sees the secret store. - Even better, let the application read secrets at runtime (External Secrets Operator), so the pipeline never handles them.
Why โ Each step away from Jenkins reduces how many places hold the secret.
Interview tip โ Mention least privilege on the IAM policy per environment.
Q74 Your Jenkins exposes the TCP agent port 50000 to the internet for remote agents. What do you change?
Beginner
Situation read โ Unnecessary exposed port.
What I'd do โ
- Switch agents to WebSocket (
-webSocket) so they connect over HTTPS 443. - Disable the TCP agent port (
jenkins.slaveAgentPort: -1in JCasC). - Close the firewall rule.
Why โ One HTTPS endpoint behind the proxy with TLS is simpler to secure.
Interview tip โ Mention agent secrets still authenticate the connection either way.
Operations: scale, HA, upgrades & performance
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q75 Jenkins is a single VM with local disk and no backups. The business wants an RTO of 1 hour. Design recovery.
Advanced
Situation read โ Make the controller reproducible and protect what is not.
What I'd do โ
- Codify: controller image with plugins, JCasC, Job DSL for jobs.
- Externalize: credentials to a secret store, artifacts to Nexus/S3.
- Back up
JENKINS_HOME(minus workspaces) nightly to versioned S3; keepsecrets/encrypted. - Runbook: provision a new controller (Terraform/Helm), restore backup or accept history loss, update DNS, verify agents.
- Run a recovery drill quarterly and time it.
Why โ With config as code, recovery is deployment plus a restore, comfortably under an hour.
Interview tip โ State RPO too: nightly backup means up to 24 h of build history loss.
Q76 Queue length spikes to 80 every morning at 9:30 and builds wait 15 minutes. How do you analyse and fix?
Intermediate
Situation read โ Capacity vs demand mismatch, or a provisioning bottleneck.
What I'd do โ
- Check
/queue/api/jsonwhy-reasons: no executors, cloud capacity reached, or pods pending. - Look at metrics: executor utilisation, cloud
containerCap, cluster autoscaler events. - Raise cloud caps and namespace quotas if the cluster has room; add node pool headroom before 9:30 (scheduled scale-up).
- Reduce demand:
abortPreviouson PRs, skip unchanged services, avoid cron jobs at 9:30.
Why โ Most queue spikes are caps or autoscaler lag, not Jenkins itself.
Interview tip โ Always ask "what is the why-reason in the queue" first.
Q77 The controller has 12 GB heap and still does full GCs every few minutes. What do you investigate?
Advanced
Situation read โ Memory pressure from data volume or a leak.
What I'd do โ
- GC logs and
jstat -gcutilto confirm old-gen growth after GC. - Heap histogram (
jcmd <pid> GC.class_histogram) or a heap dump analysed with Eclipse MAT: look forWorkflowRun,FlowNode, hugeStrings, a specific plugin's classes. - Common causes: thousands of retained builds loaded in memory, pipelines with tens of thousands of steps (huge flow graphs), massive console logs, a leaking plugin.
- Fix:
buildDiscarder, reduce step counts (fewerechoin loops), upgrade/remove the leaking plugin; only then add heap.
Why โ More heap delays the problem; data volume and leaks are usually the root.
Interview tip โ Mention that step count matters: each step creates flow nodes held in memory.
Q78 You need to upgrade from Jenkins 2.426 LTS (Java 11) to the current LTS. What is your sequence?
Intermediate
Situation read โ Two big changes: Java runtime and core/plugins.
What I'd do โ
- First switch the existing version to Java 17 (2.426 supports 17), controller and agents; validate.
- Then upgrade core in LTS steps if the gap is large, reading each upgrade guide.
- Update plugins with
jenkins-plugin-cli --jenkins-version <target> --available-updatesin staging. - Test on a restored copy of production data, then upgrade production with a backup and rollback image.
Why โ Separating Java and Jenkins upgrades isolates failures.
Interview tip โ Remember agents also need Java 17+ for current remoting.
Q79 Build history is needed for 2 years for compliance, but the controller disk is filling. What do you do?
Intermediate
Situation read โ Compliance retention conflicts with controller performance.
What I'd do โ
- Keep only recent builds in Jenkins (e.g. 30 days).
- Export build metadata and logs to long-term storage before deletion: a
post { always { } }step that uploads the log and a JSON summary to S3 with object lock, or a log shipping plugin. - Store release artifacts in the repository manager with retention policies.
- Document the evidence trail (commit, build URL, artifact digest, approver).
Why โ Jenkins is not an archive; compliance data belongs in immutable storage.
Interview tip โ Mention object lock (WORM) for audit evidence.
Q80 A plugin update caused the controller to fail on startup in production. Recover.
Intermediate
Situation read โ Need fast rollback.
What I'd do โ
- Roll back to the previous controller image (with the old
plugins.txt); with Kubernetes,helm rollbackor revert the image tag. - If plugins were installed into
JENKINS_HOMEmanually, remove the bad.jpifromplugins/(or rename to.jpi.disabled) and restart. - Check logs for the root cause (
SEVERE: Failed Loading plugin). - Reproduce in staging before retrying.
Why โ Image-based plugins make rollback a redeploy.
Interview tip โ Mention that plugin data migrations can make rollback partial; always back up before upgrades.
Q81 Your controller serves 2,000 developers and 4,000 jobs. When do you split, and how?
Advanced
Situation read โ Scale and blast radius.
What I'd do โ
- Metrics to decide: startup time, heap, UI latency, how often a restart affects everyone, plugin conflicts.
- Split by business domain into 4โ6 controllers, each generated from the same image and JCasC base with team overlays.
- Shared agent clusters (separate namespaces per controller), shared libraries, central SSO.
- A small portal or naming scheme so developers know which controller is theirs.
Why โ Smaller controllers are faster, safer to upgrade, and isolate failures.
Interview tip โ Mention CloudBees CI as the commercial path if central management is needed.
Q82 Console pages of long builds take 40 seconds to load and freeze browsers. How do you fix it?
Beginner
Situation read โ Huge logs.
What I'd do โ
- Reduce noise:
mvn -B -qor-ntp(no transfer progress),npm ci --no-progress, avoidset -xin loops. - Write verbose output to files and archive them compressed.
- Use the Pipeline Graph View to jump to the failing step's log only.
- Discard old builds.
Why โ Logs are stored and rendered by the controller; less output means faster everything.
Interview tip โ -ntp for Maven is a quick win many forget.
Q83 How do you know if Jenkins is healthy? Define SLIs and alerts.
Intermediate
Situation read โ Treat Jenkins as a product with SLOs.
What I'd do โ
- SLIs: queue wait time p95, build start success (pods connect), controller availability (
/login200), UI latency, webhook-to-start latency. - Saturation: heap usage, executor utilisation, disk free, agent pods pending.
- Alerts: queue wait p95 > 5 min for 15 min, heap > 85%, disk < 15%, controller down 2 min.
- Dashboards from the Prometheus plugin in Grafana.
Why โ Users feel queue time and failures; those are the right SLIs.
Interview tip โ Mention measuring "infrastructure failure rate" separate from test failures.
Q84 A storage outage corrupted some build.xml files and jobs show errors on load. What do you do?
Advanced
build.xml files and jobs show errors on load. What do you do?Situation read โ Partial data corruption.
What I'd do โ
- Check logs for
Failed to loadwith paths; Jenkins lists unreadable data under Manage Old Data. - For corrupted build directories, move them out of
jobs/*/builds/(or restore from backup) and reload configuration from disk. - If
config.xmlfiles are corrupted, restore from backup or regenerate jobs via Job DSL. - Verify storage health and move
JENKINS_HOMEto reliable block storage.
Why โ Corrupted build records can be dropped; configs come back from code.
Interview tip โ Mention "Reload Configuration from Disk" and its effect.
Q85 Can you run two Jenkins controller replicas behind a load balancer on a shared NFS volume for HA?
Intermediate
Situation read โ A common misconception.
What I'd do โ
- Explain no: each controller keeps state in memory and writes files independently; two writers corrupt data and both run the same scheduled builds.
- Offer real options: single replica StatefulSet with fast rescheduling, warm standby with replication, multiple independent controllers, or CloudBees HA.
- Also mention NFS latency hurts Jenkins performance; prefer block storage.
Why โ Open-source Jenkins is single-writer by design.
Interview tip โ Saying "no, and here is why" earns more credit than a creative but unsafe design.
Q86 Builds slowed down after moving JENKINS_HOME to EFS/NFS. What happened and what do you do?
Advanced
JENKINS_HOME to EFS/NFS. What happened and what do you do?Situation read โ Jenkins does many small file operations (build records, flow nodes, logs); network file systems add latency to each.
What I'd do โ
- Measure with
iostat/EFS metrics; check burst credits on EFS. - Move to block storage (EBS gp3 with provisioned IOPS, or a fast CSI volume).
- Use
PERFORMANCE_OPTIMIZEDdurability to reduce writes. - Keep workspaces off the controller entirely.
Why โ Block storage gives low-latency I/O that Jenkins' write pattern needs.
Interview tip โ Mention EFS throughput modes if forced to stay on it.
Q87 Developers complain Jenkins is "down" during upgrades every month. How do you reduce disruption?
Beginner
Situation read โ Planned downtime is noticeable because of running builds and slow startup.
What I'd do โ
- Announce maintenance windows via system message (JCasC
systemMessage). - Quiet-down ahead of time, then restart when idle.
- Speed up startup: fewer plugins, fewer retained builds, faster disk.
- Upgrade quarterly with the LTS cadence, not ad hoc.
Why โ Predictable, short windows feel much better than surprise restarts.
Interview tip โ Measure startup time and make it an explicit metric.
Q88 A rogue job with while true Groovy loop is consuming controller CPU. Fix now and prevent.
Intermediate
while true Groovy loop is consuming controller CPU. Fix now and prevent.Situation read โ CPS code runs on the controller.
What I'd do โ
- Abort the build; if it ignores aborts, use
/termthen/kill. - Find it with a thread dump (
/threadDump) showing the CPS VM thread for that job. - Prevent: pipeline-level
timeoutin the standard template, code review on Jenkinsfiles, keep logic insh.
Why โ Groovy loops do not touch agents; only timeouts and aborts stop them.
Interview tip โ Explain CPS VM threads per build.
Q89 You need to move 300 jobs from an old controller to a new Kubernetes-based one with minimal disruption. Plan it.
Advanced
Situation read โ Migration with parallel run.
What I'd do โ
- Build the new controller from code (image, JCasC, Job DSL); recreate jobs as multibranch where possible.
- Credentials: recreate in the new store or external provider; do not copy
secrets/unless you migrateJENKINS_HOMEwholesale. - Migrate team by team: switch their webhooks and branch protection checks to the new controller, keep the old one read-only for history.
- Decommission after a retention period, with history exported.
Why โ Team-by-team cutover limits risk and lets you fix issues incrementally.
Interview tip โ Mention status check names may change, requiring branch protection updates.
Q90 The controller restart takes 25 minutes. How do you bring it down to under 5?
Advanced
Situation read โ Startup loads every job and build record and initializes plugins.
What I'd do โ
- Measure with startup logs (
Started initialization,Loaded all jobs,Completed initialization) to see which phase is slow. - Discard old builds and orphaned branch jobs; job loading is usually dominant.
- Remove unused plugins; check for plugins doing heavy work on start.
- Fast storage, enough heap, and avoid
init.groovy.dscripts doing slow API calls.
Why โ Startup time scales with items, builds and plugins.
Interview tip โ Quote "Loaded all jobs" timing from logs as your diagnostic.
Integrations & delivery
๐ฅ Learn this hands-on with DevOps Shack โ YouTube @devopsshack ยท Hindi @shackverse ยท Courses at devopsshack.com
Q91 The SonarQube quality gate step waits until timeout on every build, even though analysis completes. Design the correct integration.
Intermediate
Situation read โ SonarQube is not calling back Jenkins.
What I'd do โ
- Configure a SonarQube webhook to
https://jenkins.example.com/sonarqube-webhook/(trailing slash), with a secret matching the Jenkins Sonar server config. - Ensure network connectivity from SonarQube to Jenkins.
- Keep
waitForQualityGatein the same build afterwithSonarQubeEnv, withtimeout(time: 10, unit: 'MINUTES'). - Run the gate step outside the agent pod if possible to avoid holding resources.
Why โ The step is event-driven; without the webhook it only times out.
Interview tip โ Mention report-task.txt linking the analysis to the build.
Q92 You need to publish Java artifacts: snapshots on every main build, releases on tags. Design with Nexus.
Intermediate
main build, releases on tags. Design with Nexus.Situation read โ Two repositories with different policies.
What I'd do โ
pom.xmldistributionManagementwithmaven-snapshotsandmaven-releasesURLs.- Pipeline: on
main,mvn -B deploywith-SNAPSHOTversion; on tagv1.4.0, set version fromTAG_NAME(mvn versions:set -DnewVersion=1.4.0) and deploy to releases. - Nexus: releases disallow redeploy, snapshots have cleanup policies.
- Credentials via settings.xml from Config File Provider with credential substitution.
Why โ Immutable releases plus disposable snapshots is the standard Maven model.
Interview tip โ Mention that redeploying a release returning 400 is a feature.
Q93 Developers want to deploy to Kubernetes from Jenkins, but security does not want cluster-admin kubeconfigs in Jenkins. What do you propose?
Advanced
Situation read โ Reduce or remove cluster credentials in CI.
What I'd do โ
- Preferred: GitOps. Jenkins builds, scans, pushes and then commits the new tag to a config repo (or opens a PR for prod); Argo CD in the cluster pulls and applies.
- If push-based is required: per-namespace service accounts with
editRoleBindings only in target namespaces, used by deploy pod templates (in-cluster) or short-lived tokens (kubectl create token deployer --duration=15missued by an automation). - No cluster-admin anywhere in Jenkins.
Why โ GitOps keeps cluster credentials inside the cluster and adds drift correction.
Interview tip โ Explain the Jenkins role becomes "CI and promotion", Argo CD does "CD".
Q94 Trivy blocks a release because of a HIGH CVE in a base image package with no fix available. Business wants to ship. What do you do?
Intermediate
Situation read โ Risk decision, not a pipeline bug.
What I'd do โ
- Check exploitability: is the package used at runtime, is it reachable?
- If no fix exists,
--ignore-unfixedalready skips it; if it is flagged anyway, consider a different base (distroless, newer minor). - If accepting, add the CVE to
.trivyignorewith a justification and expiry comment, approved by security. - Track it and remove the exception when a fix ships.
Why โ Gates should block by default and allow documented, time-boxed exceptions.
Interview tip โ Mention VEX documents as the formal way to state non-exploitability.
Q95 Image builds take 9 minutes in Kubernetes pods because nothing is cached. How do you add caching with Kaniko?
Intermediate
Situation read โ Ephemeral pods lose the layer cache.
What I'd do โ
- Enable Kaniko's registry cache:
/kaniko/executor --context dir://$WORKSPACE --dockerfile Dockerfile \ --destination $IMAGE:$TAG --cache=true --cache-repo=$REGISTRY/cache/shack-app - Order the Dockerfile so dependency install layers come before source copy.
- Use a base image mirror in the internal registry.
- For BuildKit, use
--export-cache type=registryand--import-cache.
Why โ A registry-backed cache survives pod deletion.
Interview tip โ Mention cache repos need their own retention policy.
Q96 A pipeline should promote the exact image that passed staging to production, not a rebuild. How do you guarantee it?
Intermediate
Situation read โ Immutable artifact promotion.
What I'd do โ
- Build once and record the digest:
crane digest $IMAGE:$TAGand store it inenv.IMAGE_DIGESTand the build description. - Deploy to staging and prod by digest (
image@sha256:...). - Optionally copy/tag the image into a prod registry with
crane copywithout rebuilding. - Prod deploy job takes the digest as a parameter, verifies the signature.
Why โ Digests are immutable; tags can be overwritten.
Interview tip โ Say "same digest in every environment" explicitly.
Q97 Your SonarQube analysis must decorate PRs with comments and fail PR builds on new issues only. How do you configure the pipeline?
Advanced
Situation read โ PR analysis needs PR parameters and an edition that supports it.
What I'd do โ
- Use SonarQube Developer Edition or above (or SonarQube Cloud); Community Build lacks branch/PR analysis natively.
- Pass PR parameters on PR builds:
sonar-scanner -Dsonar.pullrequest.key=$CHANGE_ID \ -Dsonar.pullrequest.branch=$CHANGE_BRANCH -Dsonar.pullrequest.base=$CHANGE_TARGET - Configure the GitHub integration in SonarQube for decoration.
- Quality gate on "new code" conditions;
waitForQualityGate abortPipeline: true.
Why โ New-code gates stop regressions without forcing teams to fix legacy debt first.
Interview tip โ Many Sonar plugins auto-detect PR params in Jenkins multibranch; still know the properties.
Q98 You need to run end-to-end tests against an ephemeral environment per PR and clean it up reliably. Design it.
Advanced
Situation read โ Preview environments tied to PR lifecycle.
What I'd do โ
- On PR build: create namespace
pr-${CHANGE_ID}, deploy with Helm using the PR image tag, run E2E tests. - In
post { cleanup { } }: optional teardown; better to keep the environment while the PR is open. - A scheduled cleanup job deletes namespaces whose PR is closed (query GitHub API) or older than N days; label namespaces with
pr,created-at. - ResourceQuota per preview namespace.
Why โ post cleanup is not enough (aborted builds, controller restarts), so a reaper job is essential.
Interview tip โ Mention cost controls on preview environments.
Q99 Developers want Jenkins to post the Trivy and Sonar summary on the PR. How?
Intermediate
Situation read โ Feedback in the PR improves response.
What I'd do โ
- Use the GitHub Checks plugin
publishChecks name: 'Trivy', title: 'Image scan', summary: readFile('trivy-summary.md'), conclusion: 'FAILURE'. - Or
pullRequest.comment()via the Pipeline GitHub plugin, or call the GitHub API withcurland the GitHub App token. - Keep the full report as an archived artifact and link it.
Why โ Developers act on feedback they see without opening Jenkins.
Interview tip โ Mention avoiding comment spam by updating one comment.
Q100 A Helm-based deploy stage occasionally fails with a stuck release and blocks all later deploys. Design the stage to be robust.
Intermediate
Situation read โ Helm leaves the release in pending-upgrade if interrupted.
What I'd do โ
- Use
helm upgrade --install --atomic --timeout 5m --waitso failed upgrades roll back automatically. - Use
lock(resource: "deploy-${ENV}")so two builds never upgrade the same release concurrently. - Put a stage timeout slightly longer than Helm's timeout so Jenkins does not kill Helm mid-operation.
- Document recovery:
helm history,helm rollback <release> <rev>.
Why โ Atomic upgrades plus locks remove the two common causes of stuck releases.
Interview tip โ Mention --atomic (renamed --rollback-on-failure in Helm 4) so you sound current.