Jenkins Hour 2: Pipeline Core

Building on the Lesson 1 ~/jenkinslab (jenkins + agent1 + gitea) environment, refactor myapp’s Jenkinsfile from “it runs” to “it can be reviewed”: understand the CPS execution model, master Declarative directives, parallel and matrix, artifacts and stash, containerized builds, and Multibranch + Gitea Webhook + PR builds
Jenkins LTS 2.580.2Pipeline: Groovy 4403.v4717…Declarative 2.2293.v6e71…Docker Pipeline 653.v2f2c…Gitea 286.v0740…Verified against jenkins.io and plugins.jenkins.io · 2026-11-16
Overall learning goals
  • Explain the Pipeline’s execution model: the Jenkinsfile is CPS-transformed, then interpreted on controller the controller,sh steps such as these run via durable task on agent the agent; state is written to program.dat and FlowNodes, so the controller can recover after a restart; understand NotSerializableException,@NonCPS and the trade-offs of the three durability levels.
  • Be able to write and read Declarative and Scripted syntaxes, know the advantages of Declarative (validation, Restart from Stage, the directive generator, etc.), and when to use script {}.
  • Master agent,environment (including credentials()),parameters,options,when (including beforeAgent), and predict whether a stage will run and where it runs.
  • Use parallel,matrix,failFast,catchError/unstable to organize stages, shortening feedback without hiding failures.
  • Distinguish workspace, stash, archived artifacts, fingerprints by lifecycle and use case, and use junit,archiveArtifacts,cleanWs to manage outputs.
  • Use the Docker Pipeline plugin on linux docker agent1 to run a containerized agent (agent { docker } / docker.inside), build and smoke-test myapp image, and explain docker run … cat + docker exec ’s real mechanism and the security cost of the Docker socket.
  • Connect lab/myapp to Multibranch Pipeline: Gitea branch source,http://jenkins:8080/gitea-webhook/post Webhook, PR builds (PR-1,CHANGE_ID), fork PR trust policy, and complete a CI readiness review.

1-hour time allocation

#TimeModuleCore contentAnimation / interactionLab (~/jenkinslab)
0Before classBridge & warm-upStart the Lesson 1 compose environment, restore jcli and tokens, confirm the Docker Pipeline, Gitea, Pipeline Graph View and Workspace Cleanup plugins, and verify agent1’s Docker capability and working-directory volumeEnvironment self-check listjcli: check plugins and agent1
100–06Pipeline Architecture: CPS, Groovy and PersistenceCPS transform, Groovy on the controller, durable task on agents, program.dat, resume, durability, NotSerializableException, @NonCPS, sandboxCore animation: CPS execution and persistence (including restart recovery and serialization failures)Restart the controller and observe recovery; deliberately trigger NotSerializableException
206–13Declarative and Scripted Syntaxpipeline/stages/steps/post vs node/stage, script block, validation timing, Replay, Restart from Stage, directive generatorSyntax comparator: click a structure to see both formsWrite the same flow twice and compare
313–21agent, environment, parameters and whenagent none/label/docker, environment and credentials(), five parameter types, options, when conditions and beforeAgentwhen evaluator: branch/parameter/trigger → which stages runParameterized myapp pipeline
421–28Parallel, matrix and stage controlparallel, failFast, parallelsAlwaysFailFast, matrix axes/excludes, catchError/unstable/warnError, retry/timeoutParallel timeline: failFast and exclude togglesPython 3.12/3.13 matrix tests
528–35Artifacts, stash and workspace managementworkspace @2/@tmp, stash/unstash, archiveArtifacts, fingerprint, junit, buildDiscarder, cleanWs, preserveStashesFile flow: workspace ↔ stash ↔ artifact repositoryTest reports + artifact archiving + stash across agents
635–42Docker builds and containerized agentsagent docker/dockerfile, reuseNode, docker.inside mechanics, -u uid:gid, --volumes-from, docker.build/withRun/withRegistry, socket risksdocker.inside command-by-command animationBuild myapp image + redis smoke test
742–50Multibranch, Webhooks and PR buildsbranch source and Jenkinsfile discovery, Gitea Server configuration, Webhooks, PR head/merge, fork trust, BRANCH_NAME/CHANGE_*, commit statusEvent flow: push / PR / fork PRmyapp Multibranch + Gitea Webhook + PR
850–60CI readiness review and common failuresReview checklist, common errors, Replay and Restart from Stage debugging, interactive troubleshooting treeReadiness scorecard + troubleshooting treeFault injection and fixes
—After classCheat sheet · Capstone labDeliver a myapp Multibranch pipeline that passes reviewFinal quiz (12 questions)Capstone lab

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key syntax / commandsLab
Explain CPS execution and persistence✓✓·····✓durabilityHint,@NonCPSM1 restart recovery
Read and write Declarative / Scripted·✓✓✓·✓·✓pipeline {},node {},script {}M2 two syntax forms
agent selection and labels✓·✓✓✓✓·✓agent { label 'linux && docker' }M3
environment / credentials / parameters··✓··✓✓✓credentials('gitea-myapp'),params.XParameterized pipeline
Conditional execution: when··✓✓·✓✓✓when { branch 'main'; beforeAgent true }M3 / M7
Parallel and matrix···✓✓··✓parallel,matrix,failFastPython version matrix
Artifacts, test reports, stash···✓✓✓·✓junit,archiveArtifacts,stashM5
Containerized builds and images··✓✓·✓·✓agent { docker },docker.buildmyapp image smoke test
Multibranch / Webhook / PR··✓···✓✓/gitea-webhook/post,CHANGE_IDM7 PR builds
Troubleshooting and review✓✓✓✓✓✓✓✓Replay, Restart from Stage, Pipeline Graph ViewM8 fault injection

Topics not covered in this lesson (and where to learn them)

TopicWhy it is not in this lessonWhere to learn it
controller/agent/executor/queue basics, setup wizard, plugin system, first Jenkinsfile, credentials basicsCovered in Lesson 1Lesson 1
Pushing to ACR/ECR, deploying to Container Apps/AKS/ECS/EKS, cloud identityBelongs to “Moving to the Cloud”Lesson 3 (Azure),Lesson 4 (AWS)
Shared Libraries, JCasC, Job DSL, dynamic Pod agents with the Kubernetes pluginBelongs to “Configuration as Code and Jenkins on Kubernetes”Lesson 5
Authorization strategies, Script Security approval process, supply chain and auditingBelongs to enterprise security governanceLesson 6
Builds stuck in the queue, controller performance, thread dumps and GC analysisRequires first understanding this lesson’s execution modelLesson 7 · Lesson 8 (questions & interviews)
Writing Dockerfiles, multi-stage builds, image slimmingKnowledge about containers themselvesDocker 8 hours
Equivalent syntax in GitHub Actions / Azure PipelinesThis lesson only mentions it in a comparison tableGitHub course · Azure DevOps course

How to use this courseware

10 pages per module
Principles · Diagrams · Animation · Commands · Labs · Production cases · Troubleshooting · Quiz · Narration · Video. Read “Principles” and “Animation” first, then do the “Labs”. All labs are in the same lab/myapp repository’s Jenkinsfile, accumulating changes; by the end you get a reviewable pipeline.
Learning progress
A quiz score ≥ 70% or clicking “Mark this module complete” counts toward progress, saved in this browser (cleared on refresh if the browser blocks local storage).
Chinese narration
The “Narration” page reads the course script aloud using the browser’s built-in Web Speech API (en-US), and English terms are pronounced with en-US; without a Chinese voice pack, the script can still be read or passed to a TTS tool.
Version notes This lesson is based on Jenkins LTS 2.580.2 (released 2026-10-28; requires Java 21 or 25; Java 17 is no longer supported from 2.555.1 onward) as the baseline, official image jenkins/jenkins:2.580.2-jdk21 (the tag used in Lesson 1’s compose.yaml); the current weekly is 2.590. Plugin versions follow plugins.jenkins.io as of 2026-11-16: Pipeline: Groovy (workflow-cps) 4403.v471713a_cea_19, Pipeline: Job 1624.ve973eb_34e031, Pipeline: Declarative 2.2293.v6e7193cec599, Pipeline: Nodes and Processes 1479.v56e587f413a_7, Docker Pipeline 653.v2f2c08eff0ec, Gitea 286.v0740a_413c1eb_, Git 5.11.0, Pipeline: Multibranch 842.v3a_b_59b_57b_e6e, Branch API 2.1303.v9f3b_95dc329d, JUnit 1463.v7508416a_349c, Pipeline Graph View 1134.v63b_71c6f549b_. Note: the latest JUnit and Pipeline Graph View require core ≥ 2.589 (weekly); on 2.580.2 LTS, the update center automatically offers earlier versions compatible with the LTS,so do not chase weekly just for plugins.

Module 0 · Bridge & warm-up (Lesson 1 environment)

Confirm that the three services in ~/jenkinslab are still running, install this lesson’s plugins, and check whether agent1 can safely run containerized agents
Before class ≈ 10 minDocker ComposeCost: 0 (all local)
Prerequisites (reusing the end state of Lesson 1 ~/jenkinslab)
  • Compose project jenkinslab (~/jenkinslab/compose.yaml) three services: jenkins (jenkins/jenkins:2.580.2-jdk21,127.0.0.1:8080 and 127.0.0.1:50000, volume jenkins_home); agent1 (self-built image jenkinslab/agent1:jdk21, based on jenkins/inbound-agent, with python3 and docker CLI, inbound connection, keys in .env ’s AGENT1_SECRET, via DOCKER_GID access to the mounted host docker.sock, working-directory volume agent1_work:/home/jenkins/agent, 2 executors, label linux docker); gitea (gitea/gitea:28.4, sqlite,127.0.0.1:3000,ROOT_URL=http://localhost:3000/, already set GITEA__webhook__ALLOWED_HOST_LIST=private).
  • The Built-In Node’s executor count is 0; admin admin, API token is in ~/jenkinslab/.secrets/jenkins-token; Gitea user lab ’s token (scope write:repository) is in ~/jenkinslab/.secrets/gitea-token; credentials gitea-myapp (username lab + token).
  • private repository lab/myapp (Jenkins accesses it via http://gitea:3000/lab/myapp.git access), local working copy ~/jenkinslab/myapp: app.py (Flask + gunicorn, port 5000,/healthz returns {"status": "ok"},REDIS_HOST),requirements.txt,requirements-dev.txt,pytest.ini,tests/test_app.py (two test cases, no Redis needed),Dockerfile, and the full Lesson 1 Jenkinsfile (Test → Build image myapp:1.0/myapp:$BUILD_NUMBER → Smoke test → Archive).
  • Jenkins job myapp (Pipeline script from SCM), the one defined in Lesson 1 jcli function, exported ~/jenkinslab/plugins.txt.
Cost · Permissions · Risk · Cleanup This lesson runs entirely on this machine,with no cloud cost. Requires local Docker permissions. The biggest security risk carries over from Lesson 1: agent1 mounts the host /var/run/docker.sock, so anyone who can modify the Jenkinsfile effectively has root on the host—only do this on a personal lab machine; Module 6 discusses production alternatives. For cleanup, see the last step of the “Capstone Lab” (stop services only; do not delete volumes).

Step 1: Start and check the Lesson 1 environment

cd ~/jenkinslab
docker compose up -d
docker compose ps --format 'table {{.Service}}\t{{.Image}}\t{{.State}}'
curl -s -o /dev/null -w 'jenkins %{http_code}\n' http://localhost:8080/login
curl -s -o /dev/null -w 'gitea   %{http_code}\n' http://localhost:3000/api/v1/version
SERVICE   IMAGE                           STATE
agent1    jenkinslab/agent1:jdk21         running
gitea     gitea/gitea:28.4                running
jenkins   jenkins/jenkins:2.580.2-jdk21   running
jenkins 200
gitea   200

Step 2: Restore jcli and token variables

In a newly opened terminal, redefine the jcli function from Lesson 1 Module 2 (runs the CLI inside the jenkins container, passing the token via environment variables; if already saved in ~/.bashrc you can skip), and put the token into the current shell’s variable for this lesson’s curl commands:

jcli() {
  docker compose -f ~/jenkinslab/compose.yaml exec -T \
    -e JENKINS_USER_ID=admin -e JENKINS_API_TOKEN="$(cat ~/jenkinslab/.secrets/jenkins-token)" \
    jenkins java -jar /var/jenkins_home/jenkins-cli.jar -s http://localhost:8080/ "$@"
}
export JENKINS_TOKEN="$(cat ~/jenkinslab/.secrets/jenkins-token)"
export GITEA_TOKEN="$(cat ~/jenkinslab/.secrets/gitea-token)"
jcli version && jcli who-am-i | head -n 1
2.580.2
Authenticated as: admin

This lesson’s curl access http://127.0.0.1:8080 (same as localhost:8080 ). jcli … < file redirection works properly, because the function uses exec -T, so stdin is passed into the container.

Step 3: Confirm the plugins used in this lesson

Plugin IDPurposeSource
docker-workflow (Docker Pipeline)agent { docker },docker.inside/build/withRun/withRegistryInstalled in Lesson 1 Module 3
giteaGitea branch source, Webhook endpoint /gitea-webhook/post, commit status write-backInstalled in Lesson 1 Module 3
pipeline-graph-view,ws-cleanup,timestamper,junit,workflow-aggregatorvisualization,cleanWs(),timestamps(), test reports, the Pipeline suiteRecommended plugins from the setup wizard
jcli list-plugins | grep -E '^(docker-workflow|gitea|pipeline-graph-view|ws-cleanup|workflow-cps|pipeline-model-definition|junit) '
# Install whichever are missing (already installed ones are skipped), then re-export plugins.txt per Lesson 1 Module 3
# jcli install-plugin docker-workflow gitea pipeline-graph-view ws-cleanup -deploy && jcli safe-restart
docker-workflow             Docker Pipeline                  653.v2f2c08eff0ec
gitea                       Gitea Plugin                     286.v0740a_413c1eb_
junit                       JUnit Plugin                     …
pipeline-graph-view         Pipeline Graph View              …
pipeline-model-definition   Pipeline: Declarative            2.2293.v6e7193cec599
workflow-cps                Pipeline: Groovy                 4403.v471713a_cea_19
ws-cleanup                  Workspace Cleanup Plugin         0.49

Step 4: Verify agent1’s Docker capability and working-directory volume

Containerized agents (Modules 3 and 6) have two prerequisites, both already met by Lesson 1’s compose.yaml; here we only verify: agent1 has docker the CLI and can connect to the host daemon; agent1’s working directory is on a Docker volume (Module 6 explains: when Docker Pipeline detects it is running inside a container, it uses --volumes-from agent1 to mount the same volume into the build container).

cd ~/jenkinslab
docker compose exec agent1 docker version --format 'client {{.Client.Version}} / server {{.Server.Version}}'
docker compose exec agent1 id
docker inspect agent1 --format '{{range .Mounts}}{{.Type}} {{.Destination}}{{println}}{{end}}'
client 29.x / server 29.x
uid=1000(jenkins) gid=1000(jenkins) groups=1000(jenkins),988
volume /home/jenkins/agent
bind /var/run/docker.sock

The 988 in groups comes from Lesson 1 .env in the DOCKER_GID (varies per machine). If docker version reports permission denied, regenerate per Lesson 1 Module 0 .env the DOCKER_GID and docker compose up -d agent1.

Step 5: Sync the local repository

cd ~/jenkinslab/myapp
git switch main && git pull --ff-only && ls && git log --oneline -3
Dockerfile  Jenkinsfile  app.py  pytest.ini  requirements-dev.txt  requirements.txt  tests
4c1e9a2 Lesson 1: full CI (test, image, smoke, archive)
…

On the host, the remote address is http://localhost:3000/lab/myapp.git (ROOT_URL); Jenkins and agent1 use in the compose network http://gitea:3000/lab/myapp.git—the “two URLs” that Lesson 1 emphasized.

Warm-up: answer from memory (30 seconds)

What stages does a build go through from trigger to result?

Trigger → enter queue → match node by label → allocate executor → prepare workspace → execute steps → produce logs/artifacts → result (SUCCESS/UNSTABLE/FAILURE/ABORTED). Module 1 of this lesson zooms into the “execute steps” box: which code runs on the controller and which runs on agents.

The top level of the Lesson 1 Jenkinsfile says agent { label 'linux && docker' }, and tests use agent1’s built-in python3 directly. Why change this in this lesson?

A top-level agent keeps the whole pipeline (including future approval waits) occupying agent1’s executor; tests are tied to agent1’s python3 version, so 3.12 and 3.13 cannot be verified together. Module 3 changes the top level to agent none + per-stage agent selection; Modules 4 and 6 use containerized agents to run multiple Python versions.

Environment self-check list

Module 1 · Pipeline Architecture: CPS, Groovy and Persistence

00:00 – 06:00 · A Jenkinsfile is not a script that runs on an agent: its Groovy is interpreted step by step on the controller, and its state can be saved to disk at any time and resumed after a restart
6 minworkflow-cps 4403.v4717…Core animation★★★★★
Learning goals
  • State where each of the three kinds of code runs in a Pipeline build: Groovy glue code (the CPS VM on the controller), controller-side steps (echo,error,input,timeout timing, etc.), agent-side steps (sh/bat/powershell, run via durable task).
  • Explain why the CPS (Continuation-Passing Style) transform lets a pipeline resume after a controller restart, and its cost: local variables must be serializable, otherwise you get java.io.NotSerializableException.
  • Use correctly @NonCPS, the three durability levels (MAX_SURVIVABILITY / SURVIVABLE_NONATOMIC / PERFORMANCE_OPTIMIZED) and disableResume().
  • Understand why the Groovy sandbox (Script Security) rejects Jenkins.instance and similar calls.
Prerequisites: The controller / agent / executor concepts from Lesson 1. Importance:★★★★★ (all later troubleshooting builds on this model)

What: Pipeline = a “pausable Groovy program” running on the controller + steps dispatched to agents

Pipeline plugin (technical name workflow-*) runs the Jenkinsfile as a Groovy program, but does not hand it directly to the Groovy runtime: Pipeline: Groovy (workflow-cps) first performs a CPS transform, rewriting every method call, loop and closure into a chain of “continuation” objects, then run by the controller’s CPS VM thread interpreting step by step. When it encounters sh such a step that must wait, the interpreter takes the entire current call stack and local variables serializes them to the build directory’s program.dat, then yields the thread until the step finishes and continues.

Code / stepWhere it runsNotes
if, loops, string concatenation,def variables, custom methodscontroller (CPS VM)Consumes the controller’s CPU and heap; official best practice quote: “Groovy code always executes on controller”.
echo,error,stash ’s scheduling,input,milestone,timeout timingcontrollerstep implementations run inside the controller JVM; stash ’s file packaging/transfer involves both the agent and the controller.
node / agentStarted by the controller, occupies the agent’s executorRequests a “heavyweight” executor from the queue and locks a workspace. The pipeline itself only occupies a controller-side flyweight executor (not counted in the executor count).
sh / bat / powershellagentExecuted by Pipeline: Nodes and Processes (workflow-durable-task-step) starts a wrapper script on the agent via remoting, and writes output to <workspace>@tmp/durable-xxxx/jenkins-log.txt, and the exit code is written to jenkins-result.txt; the controller polls and reads them.
readFile,writeFile,fileExists,dirthe agent’s file system, with results returned to the controllerreadFile brings the entire file content back into controller memory as a string—avoid for large files.

Why: why is it so complex?

  • Resumability (durability): a deployment pipeline can run for hours and may stop at input while waiting for approval for days. During a controller upgrade or restart, running builds must not all fail. CPS turns the Groovy program’s “execution position” into data that can be saved.
  • Processes on the agent do not depend on the controller connection: durable task uses nohup -style wrapping so the shell process runs independently of the remoting channel. When the controller restarts or the network blips, the processes on the agent make test keep running and keep writing to the log.
  • Visualization: every step is a FlowNode FlowNode, persisted in the build directory; Pipeline Graph View, Stage View and Restart from Stage all depend on them.

How: where a build is stored on disk

$JENKINS_HOME/jobs/<job>/builds/<n>/
├── build.xml              # build record (result, parameters, Actions)
├── log                    # console log
├── program.dat            # CPS program state (exists while running; deleted on completion)
└── workflow/ or workflow-completed/   # FlowNode storage (start/end nodes of each step)

agent1:<workspace>@tmp/durable-1a2b3c4d/
├── script.sh              # script content of the sh step
├── jenkins-log.txt        # output (the controller reads incrementally by offset)
└── jenkins-result.txt     # exit code written after the process ends

Cost: the four rules CPS imposes

  1. Local variables must be serializable. When calling sh,sleep,input or other async steps, every variable still in scope gets written into program.dat. java.util.regex.Matcher,groovy.json.internal.LazyMap (JsonSlurper ’s result), iterators, network connections, etc. are not serializable → java.io.NotSerializableException.
  2. @NonCPS Methods are not CPS-transformed, and run in a single Java call from start to finish: non-serializable objects can be used, but Pipeline steps cannot be called (sh,echo etc.), otherwise behavior is abnormal; if interrupted, it re-runs from the beginning.
  3. Some Groovy constructs are not supported by CPS: passing CPS closures to Java methods (such as list.toSorted { … }), calling CPS methods inside a constructor, and CPS-ified toString(). The log shows a expected to call … but wound up catching … warning.
  4. Groovy is slow and occupies the controller: interpreted execution is much slower than native Groovy. Heavy work (parsing large JSON, looping over thousands of files, HTTP calls) should be moved to agent-side sh (such as jq,curl).

durability levels (Speed/Durability Settings)

LevelWrite methodAfter a controller crash (abnormal shutdown)Best for
MAX_SURVIVABILITY (default)Every step atomically writes FlowNode and program stateCan resumeDeployments and pipelines with input approval steps (critical pipelines)
SURVIVABLE_NONATOMICWrites each step, but without atomic writesUsually resumable; a small chance of data loss on OS crashOn network file systems JENKINS_HOME
PERFORMANCE_OPTIMIZEDGreatly reduces disk I/O, saves only at key momentsMay not be resumable, running builds fail or lose some records; a graceful shutdown (safe-restart) still allows resumeOfficial guidance: most build and test pipelines use this (just rerun on failure)

Where to set: globally Manage Jenkins → System → Pipeline Speed/Durability Settings; per job Custom Pipeline Speed/Durability Level property; Multibranch branch property strategy, or in the Jenkinsfile options { durabilityHint('PERFORMANCE_OPTIMIZED') } (takes effect on the next run). The official docs also note that Performance Optimized may mask serialization problems; for local debugging, the default level makes them easier to catch NotSerializableException.

When: when you need to care about these

  • When you see NotSerializableException,expected to call … but wound up catching, or RejectedAccessException .
  • Controller memory/CPU is high, or builds are “stuck in Groovy” (covered in depth in Lesson 7).
  • When planning to upgrade or restart the controller: use safe-restart to let running pipelines save to disk before stopping.

Comparison with similar technologies

Jenkins PipelineGitHub ActionsAzure Pipelines
Process definitionGroovy DSL (Declarative/Scripted), interpreted on the controllerYAML, orchestrated by the serverYAML, orchestrated by the server (templates expanded at queue time)
Step executiondurable task on the agentprocess on the runnertask on the agent
Orchestration service restartCPS state saved to disk, resumableManaged service, invisible to usersManaged service, invisible to users
Arbitrary code logicYes (Groovy, subject to sandbox restrictions)Expressions + script stepsExpressions + script steps

For comparison details, see GitHub courseand Azure DevOps course.

Common misconceptions① “The Jenkinsfile runs on the agent”—only steps run on agents; Groovy runs on the controller. ② “@NonCPS makes code faster, so add it everywhere”—it forbids calling steps, and an interruption re-runs everything. ③ “parallel makes Groovy run multithreaded”—the CPS VM is single-threaded per build; parallel branches alternate as “green threads”; real parallelism happens in agent-side sh. ④ “PERFORMANCE_OPTIMIZED restart always loses builds”—a graceful restart can still resume; the real danger is a crash.

Architecture diagram: where a Jenkinsfile statement executes

controller (jenkins container · JVM) JenkinsfileRead from Gitea(lightweight checkout) Parse + sandbox checkDeclarative validationCPS transform CPS VM threadInterpret continuations one by oneflyweight executor builds/7/program.datCall stack + local variables (serialized)River serialization · must be Serializable FlowNode storageNode for each stage / stepGraph View / Restart from Stage depend on Controller-side stepsecho · error · input · timeout timing · milestone · stash metadata · reading log offsets on the agentNo executor needed; can run outside a node remoting agent1 (labels linux docker) executor + workspace…/workspace/myapp_mainAllocated by node / agent durable task (sh)script.sh → background wrapper processoutput → jenkins-log.txtexit code → jenkins-result.txtDecoupled from the remoting connection docker CLI → host DockerModule 6: containerized agents Poll log
Figure 1-1: Groovy and flow state stay on the controller; shell processes run independently on the agent, and the controller reads output via file offsets

Sequence: one sh call and one restart

CPS VM (controller)program.datagent1 process ① Start durable task: write script.sh, run in background ② Serialize call stack and variables ③ Poll: read new content from jenkins-log.txt ④ Controller restarts Process keeps running and keeps writing logs ⑤ Deserialize, restore execution position ⑥ After agent reconnects, continue reading the log from the saved offset ⑦ Read jenkins-result.txt = 0 → step succeeded, continue to the next statement
Figure 1-2: The shell process was not interrupted during the restart; recovery depends on program.dat being fully deserializable

Core animation: CPS execution and persistence

Choose a scenario and durability level, then step through or auto-play. The highlighted box marks the currently active component; the log at the bottom simulates console output. The script for scenarios ①–③ is def major = majorOf(env.APP_VER) (@NonCPS method returning String) → node('docker') { sh 'pytest -q' } → echo 'done'; scenario ④ replaces the first line with def m = (env.APP_VER =~ /(\d+)\.(\d+)/).

controller (jenkins) JenkinsfileParse · sandbox · CPS transform CPS VM threadIdle Queuenode('docker') request program.dat(not yet written) FlowNode / console log0 nodes Build resultRunning… agent1 (linux docker) executor + workspaceUnassigned durable task———
Choose a scenario, then click “Next”.
Key observations The only difference between scenarios ② and ③ is whether the controller had a chance to save to disk before stopping; switch durability and replay ③ to see why critical deployment pipelines keep the default MAX_SURVIVABILITY. In scenario ④, the failure occurs at serialization before calling sh, not in the regex itself.

Syntax and commands related to the execution model

Syntax / commandPurposeNotes
options { durabilityHint('PERFORMANCE_OPTIMIZED') }Set this job’s durabilityTakes effect on the next run; can also be set on the job configuration page
options { disableResume() }Not resumed after controller restart; fails directlySuitable for non-idempotent steps whose state after recovery cannot be trusted
@NonCPS def f(...) { ... }Method is not CPS-transformedOnly processes data, does not call steps, returns serializable results (String/List/Map)
sh(script: '…', returnStdout: true).trim()Hand computation to the agent and fetch the outputReplaces large amounts of Groovy on the controller
readJSON / readYaml (Pipeline Utility Steps)Parse files into serializable Map/List, safer than JsonSlurper (the latter returns a LazyMap, which is not serializable); for large files, use the shell on the agent jq
jcli safe-restartWait for running steps to reach a savepoint, then restartWeb UI: /safeRestart
jcli console JOB [N] -fFollow console output in the terminalAfter restart you will see Resuming-related logs
Manage Jenkins → System → Pipeline Speed/Durability SettingsGlobal default levelWhen unset, it is MAX_SURVIVABILITY
Manage Jenkins → In-process Script ApprovalView signatures rejected by the sandbox and awaiting approvalLesson 6 covers approval governance
# View a running build’s on-disk files on the controller (replace job name and build number as appropriate)
docker compose exec jenkins ls -la /var/jenkins_home/jobs/cps-lab/builds/1/
# View the durable task directory for the sh step on agent1
docker compose exec agent1 sh -c 'ls -d /home/jenkins/agent/workspace/*@tmp/durable-* 2>/dev/null'
-rw-r--r-- 1 jenkins jenkins  2481 build.xml
-rw-r--r-- 1 jenkins jenkins   913 log
-rw-r--r-- 1 jenkins jenkins 18764 program.dat
drwxr-xr-x 2 jenkins jenkins  4096 workflow
/home/jenkins/agent/workspace/cps-lab@tmp/durable-7f3c2a10

How to verify: After the build finishes, program.dat disappears, and the durable directory is deleted. Common mistake: Assuming /var/jenkins_home/workspace/ has build files. When the pipeline runs on agent1, the workspace lives under the agent’s Remote root directory. Production use: When troubleshooting “build resume failed”, check these two locations first.

Lab 1: see recovery and serialization failures for yourself (about 6 min)

Create a Pipeline job with an inline script (submit the job XML with jenkins-cli, setting sandbox to true):
cd ~/jenkinslab
cat > cps-lab.xml <<'EOF'
<flow-definition plugin="workflow-job">
  <description>Lesson 2 Module 1: CPS recovery lab</description>
  <definition class="org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition" plugin="workflow-cps">
    <script>
echo "Groovy runs on the controller"
node('docker') {
  sh 'for i in $(seq 1 40); do echo "tick $i on $(hostname)"; sleep 3; done'
}
echo 'done'
    </script>
    <sandbox>true</sandbox>
  </definition>
</flow-definition>
EOF
jcli create-job cps-lab < cps-lab.xml
jcli build cps-lab
Restart the controller about 20 seconds after the build starts running (Compose sends SIGTERM, and Jenkins goes through its normal shutdown process), then follow the log:
sleep 20; docker compose restart jenkins
until curl -sf -o /dev/null http://127.0.0.1:8080/login; do sleep 3; done
jcli console cps-lab 1 -f | tail -n 25
tick 6 on 3f9a1c2b7d10
tick 7 on 3f9a1c2b7d10
Resuming build at Mon Nov 16 10:42:07 UTC 2026 after Jenkins restart
Waiting for reconnection of agent1 before proceeding with build
Ready to run at Mon Nov 16 10:42:15 UTC 2026
tick 8 on 3f9a1c2b7d10
…
tick 40 on 3f9a1c2b7d10
[Pipeline] }
[Pipeline] // node
[Pipeline] echo
done
[Pipeline] End of Pipeline
Finished: SUCCESS

The shell process on agent1 did not stop during the restart: the tick count is continuous, and the controller simply resumes reading from the recorded offset in jenkins-log.txt jenkins-log.txt. Some ticks from within the restart window appear all at once after recovery.

Trigger a NotSerializableException: in the Web UI, open cps-lab → Configure and replace the script with:
def ver = '1.1.0'
def m = (ver =~ /(\d+)\.(\d+)/)      // java.util.regex.Matcher, not serializable
if (m.find()) { echo "major=${m.group(1)}" }
node('docker') {
  sh 'echo needs to save program state before it can wait on this step'
}
major=1
[Pipeline] node
…
an exception which occurred:
	in field org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.closures
	…
Caused: java.io.NotSerializableException: java.util.regex.Matcher
	…
Finished: FAILURE

If the sandbox blocks regex-related methods, you will see Scripts not permitted to use method java.util.regex.Matcher …, meaning the sandbox stopped it before serialization ever came into play—this is one reason production code should avoid this kind of processing in Groovy.

Two fixes; choose one:
// Fix A: put the non-serializable processing in a @NonCPS method, returning only a String
@NonCPS
String majorOf(String v) {
  def m = (v =~ /(\d+)\.(\d+)/)
  return m.find() ? m.group(1) : null
}
echo "major=${majorOf('1.1.0')}"
node('docker') { sh 'echo ok' }

// Fix B: hand it to the shell on the agent
node('docker') {
  def major = sh(script: "echo 1.1.0 | cut -d. -f1", returnStdout: true).trim()
  echo "major=${major}"
}
(Optional) Compare a crash: set the job’s Custom Pipeline Speed/Durability Level to Performance-optimized, restore the script from step 1, and during the build run docker compose kill -s KILL jenkins && docker compose up -d jenkins. Under PERFORMANCE_OPTIMIZED, this build may not be resumable; switch back to Maximum survivability and retry for comparison. After the lab, delete the job: jcli delete-job cps-lab.

Case 1: after upgrading the controller, all 30 deployment pipelines failed

Problem: Ops directly kill -9 ’d the controller process for an emergency upgrade; global durability was set to PERFORMANCE_OPTIMIZED (to reduce I/O on NFS). Fix: Set deployment jobs individually to MAX_SURVIVABILITY, keep build/test jobs on PERFORMANCE_OPTIMIZED; change the upgrade process to Prepare for Shutdown → wait → safe-restart. Configuration: In the deployment Jenkinsfile, explicitly write options { durabilityHint('MAX_SURVIVABILITY') }. Limitation: Recovery can only resume “the step currently waiting”; if the container hosting the agent is also rebuilt, the durable task disappears with it.

Case 2: parsing a 30 MB JSON file caused controller Full GC

Problem: The pipeline used readFile + JsonSlurper to parse a dependency scan report, and controller heap usage spiked, slowing down all builds. Fix: Official best practice states that readFile reads the file into controller memory (JsonSlurper keeps another copy). Change it to run on the agent jq '.vulnerabilities | length' report.json, returning only the numeric result to Groovy. Limitation:returnStdout also brings the output back to the controller, so keep the output short.

Case 3: after adding @NonCPS to a shared library method, “steps don’t execute”

Problem: To eliminate NotSerializableException, a developer, in a utility method that called sh , added @NonCPS, so only the first sh ran, and the logic after it ran out of order. Fix: Split the method into two parts: the pure data-processing part gets @NonCPS, and the part that calls steps stays CPS. Limitation: The official CPS Method Mismatches documentation explicitly states that @NonCPS methods should not call steps.

Common errors and fixes

java.io.NotSerializableException: java.util.regex.Matcher

Cause: When calling an async step, a non-serializable object is in scope, such as a LazyMap (JsonSlurper),Iterator,Matcher,HttpURLConnection are the most common.

Fix: Move it into @NonCPS a method that returns only String/List/Map; or, before calling the step, set the variable to null; or use readJSON (Pipeline Utility Steps) / a shell on the agent.

expected to call WorkflowScript.xxx but wound up catching org.jenkinsci.plugins.workflow.cps.CpsClosure2.call

Cause: CPS method mismatch: passing a CPS closure to a Java method that doesn’t understand CPS (such as toSorted,collectEntries in certain usages), or in @NonCPS method calls a step.

Fix: Per jenkins.io’s “Pipeline CPS Method Mismatches”: put pure Java operations such as sorting into a @NonCPS method; remove step calls from a @NonCPS method.

org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use staticMethod jenkins.model.Jenkins getInstance

Cause: The Jenkinsfile runs in the Groovy sandbox, and the internal API is rejected.

Fix: Do not access Jenkins.instance (the official best practice calls this “code misuse”); implement needed capabilities with built-in steps or plugins. Do not approve such signatures just for convenience—Lesson 6 explains that approving one is equivalent to letting scripts run with system privileges.

Build fails after restart: …Pipeline resume failed / cannot load from program.dat
docker compose logs jenkins | grep -iE 'resume|program.dat|CpsFlowExecution' | tail

Cause: Abnormal shutdown with durability set to PERFORMANCE_OPTIMIZED; or after a plugin upgrade, old serialized classes are incompatible; or the job was set to disableResume().

Fix: Rerun the build; for critical pipelines, use MAX_SURVIVABILITY; drain running builds before upgrading plugins.

Waiting for reconnection of agent1 before proceeding with build (stuck indefinitely)

Cause: The controller restored program state, but the agent the build was on has not come back online (container deleted, node renamed).

Fix: Reconnect agent1 (docker compose up -d agent1); if the agent is permanently gone, abort the build from its page. Lesson 7 covers systematic troubleshooting of agent disconnections.

Command-line tasks
1. In the Jenkinsfile, make the current job use performance-first durability, and not resume after a controller restart.
pipeline {
  agent none
  options {
    durabilityHint('PERFORMANCE_OPTIMIZED')
    disableResume()
  }
  stages { stage('noop') { steps { echo 'ok' } } }
}
2. Use jenkins-cli in the terminal to follow job cps-lab build #3’s console output.
jcli console cps-lab 3 -f
Scenario analysis
The team says, “Our Jenkinsfile has 600 lines of Groovy that calculate which microservices need to be built, and controller CPU sits at 90% year-round.” What recommendations would you give?

① Move computation to agents: use sh 'git diff --name-only … | ./ci/affected.sh' to output a short result,returnStdout and bring it back. ② Merge trivial steps (multiple echo/sh calls merged into one script), reducing FlowNodes and disk writes. ③ For build/test jobs, use PERFORMANCE_OPTIMIZED, deployment jobs stay on the default. ④ Avoid huge shared libraries and global-variable files (Lesson 5). ⑤ Use Pipeline Graph View and Lesson 7’s thread dumps to confirm hotspots.

Verified instructional videos

▶
What Is durabilityHint in Jenkins — CloudBeesTV
English · explains durabilityHint options and the trade-offs of the three levels
▶
What Is disableResume in Jenkins — CloudBeesTV
English · option to not resume builds after controller restart
▶
Complete Jenkins Pipeline Tutorial | Jenkinsfile explained — TechWorld with Nana
English · Jenkinsfile overall structure intro (recorded earlier; the UI follows the current version)

Internals of the CPS transform, program.dat and NotSerializableException: No verified dedicated video found. Please refer to this module’s animation and the official documentation below.

Official documentation

Video storyboard script (about 100 seconds)

This courseware cannot directly generate video/MP3; the storyboard and narration script below can be given to a video tool to produce.

Shot 1 · 0–20s
Visual: the Jenkinsfile text is broken into blocks, enters a gear labeled “CPS Transform” in the controller, and becomes a chain of linked small cards (continuations).
Narration: The Jenkinsfile’s Groovy doesn’t run on the agent; instead, on the controller it is transformed into a series of steps that can be paused.
Shot 2 · 20–45s
Visual: the card reaches sh and sends a package to agent1; script.sh and jenkins-log.txt appear on agent1; meanwhile the controller compresses the card chain into program.dat and saves it to disk.
Narration: When sh is called, the command runs in the background on the agent, and the controller serializes the program state to program.dat.
Shot 3 · 45–75s
Visual: the controller light goes off and back on; log lines on the agent keep increasing; program.dat is read back, and the card chain continues from where it left off.
Narration: When the controller restarts, processes on the agent are unaffected; after recovery, it continues from the saved position and log offset.
Shot 4 · 75–100s
Visual: a red Matcher object gets mixed into the card chain, and NotSerializableException pops up during compression; switch to the @NonCPS method box, where the red object exists only inside the box and only a string remains outside.
Narration: Every variable in scope must be serializable. Put non-serializable processing in a NonCPS method and return only simple results.
or score ≥ 70% on the quiz

Module 2 · Declarative and Scripted Syntax

06:00 – 13:00 · Both syntaxes run on the same CPS engine; Declarative performs structural validation before execution, trading for readability, visualization and Restart from Stage
7 minpipeline-model-definition 2.2293★★★★☆
Learning goals
  • Write the skeleton of a Declarative pipeline: pipeline → agent → stages → stage → steps → post, and know which directives may appear at which level.
  • Write the equivalent Scripted: node,stage,try/catch/finally,properties([...]),parallel map.
  • Use declarative-linter to validate the Jenkinsfile before committing; you will use Snippet Generator, Declarative Directive Generator, Replay and Restart from Stage.
  • Judge when you need script {}, and why not to pile large blocks of Groovy into Declarative.
Prerequisites: The execution model from Module 1; the first Jenkinsfile from Lesson 1. Importance:★★★★☆

What: two syntaxes, one engine

pipeline {
  agent { label 'linux && docker' }
  options { timeout(time: 20, unit: 'MINUTES') }
  stages {
    stage('Build') {
      steps { sh 'docker build -t myapp:ci .' }
    }
  }
  post {
    failure { echo 'Build failed' }
    always  { echo "Result: ${currentBuild.currentResult}" }
  }
}
properties([])                 // job properties go here
timeout(time: 20, unit: 'MINUTES') {
  node('linux && docker') {
    try {
      stage('Checkout') { checkout scm }
      stage('Build') { sh 'docker build -t myapp:ci .' }
    } catch (err) {
      echo 'Build failed'
      throw err
    } finally {
      echo "Result: ${currentBuild.currentResult}"
    }
  }
}

Declarative Provided by the Pipeline: Declarative plugin (pipeline-model-definition) provides it. It first parses the pipeline {} block into a model and validates the structure (e.g., missing stages, misspelled directives, or directives at the wrong level all fail before any step runs, and then the model is translated into calls to Scripted steps, executed by the same CPS engine. Scripted is Groovy with a step library: flexible, but errors surface only when execution reaches that line.

Why: choose Declarative by default

CapabilityDeclarativeScripted
Pre-execution structural validation / declarative-linter✓✗ (only checks Groovy syntax)
Implicit checkout scm✓ (skipDefaultCheckout , can be turned off)Requires explicit checkout scm
post conditions (always/success/failure/unstable/changed/fixed/regression/aborted/unsuccessful/cleanup)✓ Built inMust implement with try/catch/finally yourself
when,matrix,parameters,options directives✓Use if, properties, hand-written loops
Restart from Stage✓✗
Skipped stages appear as “skipped” in visualization✓✗ (stages skipped by if do not appear)
Arbitrary control flow (dynamically generated stages, complex loops)Limited (script {})✓

How: Declarative’s hierarchy rules

Directive / sectionpipeline top levelInside stageNotes
agentRequired (can be none)OptionalTop level agent none (then each stage must declare its own)
stages / stepsstages Requiredsteps,stages,parallel,matrix pick one of fourNested stages Lets a group of stages share an agent
post✓✓Executed in fixed order: always → changed → fixed → regression → aborted → failure → success → unstable → unsuccessful → cleanup
environment✓✓Module 3
options✓section (skipDefaultCheckout,timeout,retry,timestamps)Stage-level options are applied before the agent is allocated and before when is evaluated; they take effect
parameters / triggers✓✗Essentially a job property; it appears in the UI only after the first run (Module 3)
tools✓✓Automatically installs Maven/JDK/Gradle etc. (myapp uses containers instead)
input / when✗✓Stage level
script { }✗Can only be used inside steps within, embedding a Scripted Groovy block

When: when to use script {} or Scripted

  • When you need to store a step’s return value for later use: script { env.SHORT_SHA = sh(script: 'git rev-parse --short HEAD', returnStdout: true).trim() }.
  • When you need to dynamically generate parallel branches from runtime data (for example, per directory): inside script {} build a map and then call parallel.
  • Groovy beyond 10–20 lines: move it to Shared Library (Lesson 5) or a script on the agent.
  • Maintaining legacy Scripted pipelines: no need to force a rewrite, but new pipelines default to Declarative.

Developer tools

  • Snippet Generator: on any Pipeline job’s /pipeline-syntax page, choose a step, fill in the form, and generate the step code (such as withCredentials,checkout).
  • Declarative Directive Generator: on the left side of the same page, generate agent,options,when,parameters and other directives.
  • Global Variable Reference: env,params,currentBuild,scm,docker etc. global variable references (vary with installed plugins).
  • Replay: on a completed build’s page, edit the Jenkinsfile (and any loaded shared library scripts) and run again, without committing. Good for debugging,but do not forget changes made in Replay that were left outside the repository.
  • Restart from Stage: Declarative only; restarts from a top-level stage on a completed build, with earlier stages shown as skipped; stash data needs to be paired with preserveStashes() (Module 5).
  • declarative-linter: jcli declarative-linter < Jenkinsfile, or POST to /pipeline-model-converter/validate.
Common misconceptions① “Declarative is not Groovy”—it is a restricted subset of Groovy syntax; string interpolation,${} rules are exactly the same. ② “script {} more is more flexible”—each script block bypasses validation and visualization. ③ “Scripted is faster”—both use the same engine; performance depends on the amount of Groovy and the number of steps. ④ “Changes made in Replay are saved”—they apply only to that build.

How Declarative becomes execution

Jenkinsfilepipeline { … } Groovy parsingSyntax errors fail here(Scripted also has this step) Model validationDirectives / levels / required sectionsDeclarative only Translated into step callsnode / stage / checkoutpost → try/finally semantics CPS engineSame for Scriptedidentical Example: writing step { } inside a stage → “WorkflowScript: 8: Unknown stage section "step"”, 0 steps executed Example: missing one } → “unexpected token”
Figure 2-1: Declarative adds one extra “pre-execution model validation” step compared with Scripted, so structural errors do not fail halfway through the run

Declarative structure tree

pipeline agent environment options parameters/triggers stages post tools stage('x') steps parallel matrix stages agent · environment · options · when · input · post Pick one of four
Figure 2-2: Inside a stage, only one of steps / parallel / matrix / stages may be chosen

Interactive: syntax comparator

Click a requirement; the left and right sides show the Declarative and Scripted forms, with the differences explained.

Declarative
Scripted

Syntax and tool commands

Command / addressPurposeNotes
jcli declarative-linter < JenkinsfileValidate Declarative structure on the server sideUse plugins installed on the controller to check whether a directive exists
curl -u admin:$JENKINS_TOKEN -X POST -F "jenkinsfile=<Jenkinsfile" http://127.0.0.1:8080/pipeline-model-converter/validateValidate via HTTPCan be placed in a Git pre-commit hook
http://127.0.0.1:8080/job/<job>/pipeline-syntax/Snippet Generator / Directive GeneratorGenerated code matches the current plugin version
…/pipeline-syntax/globalsGlobal variable referenceenv,currentBuild,docker etc.
build page → ReplayEdit the script and run againRequires Job/Configure or Run/Replay permission
build page → Restart from StageRerun from a top-level stageDeclarative only; options { disableRestartFromStage() } can be disabled
jcli replay-pipeline JOB -n N < JenkinsfileCLI Replaystandard input is the new script
cd ~/jenkinslab/myapp
jcli declarative-linter < Jenkinsfile
Jenkinsfile successfully validated.
Errors encountered validating Jenkinsfile:
WorkflowScript: 6: Unknown stage section "step". Starting with version 0.5, steps in a stage must be in a ‘steps’ block. @ line 6, column 5.
       stage('Build') {
       ^

How to verify: The linter only checks Declarative structure and installed directive/step names; it does not execute any steps, nor does it check whether shell commands can run. Common mistake: Treating the linter as a unit test; running the linter on a Scripted file (it will report a missing pipeline block). Production use: Run it in the first stage of a PR build or in a local hook.

Lab 2: write this lesson’s Declarative baseline on the Lesson 1 myapp job (about 7 min)

Confirm the Lesson 1 job myapp (Pipeline script from SCM, repository http://gitea:3000/lab/myapp.git, credentials gitea-myapp, Script Path Jenkinsfile). Modules 3–6 keep using it for repeated builds; in Module 7 it is replaced by Multibranch and disabled.
cd ~/jenkinslab
jcli get-job myapp | grep -E '<url>|<credentialsId>|<name>|<scriptPath>'
          <url>http://gitea:3000/lab/myapp.git</url>
          <credentialsId>gitea-myapp</credentialsId>
          <name>*/main</name>
    <scriptPath>Jenkinsfile</scriptPath>

If the Lesson 1 job does not exist (for example, the environment was rebuilt), recreate it per Lesson 1 Module 5, keeping the name myapp.

Rewrite the repository’s Jenkinsfile as this lesson’s Declarative baseline (the full Lesson 1 version—Test → Build image → Smoke test → Archive—is saved in Git history; this lesson will gradually refactor it into a multi-stage, multi-agent version; the image version also goes from myapp:1.0 to 1.1):
pipeline {
  agent { label 'linux && docker' }
  options {
    buildDiscarder(logRotator(numToKeepStr: '20'))
    timeout(time: 20, unit: 'MINUTES')
    timestamps()
  }
  stages {
    stage('Info') {
      steps {
        sh '''
          echo "node=$NODE_NAME workspace=$WORKSPACE"
          git log -1 --format='%h %s'
          docker version --format 'docker server {{.Server.Version}}'
        '''
      }
    }
    stage('Build image') {
      steps {
        sh 'docker build -t myapp:ci-$BUILD_NUMBER .'
      }
    }
  }
  post {
    always  { echo "Result: ${currentBuild.currentResult}, took ${currentBuild.durationString}" }
    cleanup { sh 'docker image rm -f myapp:ci-$BUILD_NUMBER || true' }
  }
}

Note sh '''…''' Uses single quotes (not triple quotes): $NODE_NAME is expanded by the shell and does not go through Groovy interpolation. {{.Server.Version}} is a Go template for docker; Groovy does not process it inside a single-quoted string.

Validate first, then commit and build:
cd ~/jenkinslab/myapp
jcli declarative-linter < Jenkinsfile
git add Jenkinsfile && git commit -m "Lesson 2: Declarative baseline" && git push
jcli build myapp -s -v | tail -n 15
Jenkinsfile successfully validated.
…
[Pipeline] { (Build image)
[Pipeline] sh
10:51:32  + docker build -t myapp:ci-1 .
10:51:40  #9 naming to docker.io/library/myapp:ci-1 done
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Declarative: Post Actions)
[Pipeline] echo
10:51:41  Result: SUCCESS, took 9.8 sec and counting
…
Finished: SUCCESS

jcli build -s Wait for the build to finish,-v then view the console log. Declarative: Checkout SCM is the implicit checkout stage that Declarative adds automatically.

Deliberately break it once: change steps { to step {, run the linter and see Unknown stage section "step", then change it back (do not commit the broken version).
Use Replay to write a Scripted version: open the latest myapp build → Replay, replace the main script with the content below and run it, then compare how the two look in Pipeline Graph View (Scripted has no implicit checkout and no “Post Actions” stage):
node('linux && docker') {
  try {
    stage('Checkout') { checkout scm }
    stage('Info') { sh 'git log -1 --format="%h %s"' }
    stage('Build image') { sh "docker build -t myapp:ci-${env.BUILD_NUMBER} ." }
  } finally {
    sh "docker image rm -f myapp:ci-${env.BUILD_NUMBER} || true"
    echo "Result: ${currentBuild.currentResult}"
  }
}

Case 1: migrating from a 2000-line Scripted pipeline

Problem: The legacy Scripted Jenkinsfile built stage names by concatenating variables, which made the visualization messy, and after a failure the whole pipeline had to be rerun. Approach: Migrated to top-level Declarative stages (Restart from Stage can only start at a top-level stage), and moved the complex logic into vars/ steps of a shared library, so the Jenkinsfile keeps only the “orchestration”. Configuration: On PR builds, the first stage runs declarative-linter. Limitation: Truly dynamic stage structures (generated from the repository's directories) still need script { parallel(map) }.

Case 2: Replay fixed it, but the next run failed again

Problem: An on-call engineer changed one image tag line in Replay; the build succeeded, but the change was never committed, and the scheduled build failed again the next day. Approach: The team rule is that Replay is for diagnosis only; fixes must go through a PR. Configuration: Use matrix authorization (Lesson 6) to grant Run/Replay permission only to maintainers. Limitation: Having Replay permission is equivalent to being able to run arbitrary code on the agent.

Case 3: Groovy string interpolation leaks credentials

Problem:sh "curl -u $USER:$TOKEN …" Using double quotes, the token is interpolated by Groovy first, and Jenkins logs a warning A secret was passed to "sh" using Groovy String interpolation, which is insecure. Approach: Switch to single quotes so the shell expands the environment variable: sh 'curl -u "$USER:$TOKEN" …'. Limitation: Masking only applies to credential values that Jenkins knows about; transformed values (such as base64) are not masked.

Common errors and fixes

WorkflowScript: 3: Missing required section "stages" @ line 1, column 1.

Cause: The top level of the Declarative pipeline is missing stages (or misspelled as stage).

Fix: Complete the structure; generate the snippet with the Directive Generator.

WorkflowScript: 9: Expected a step @ line 9, column 11.

Cause: Inside steps a Groovy statement was written directly (such as def x = 1,if).

Fix: Wrap it in script { }, or switch to when directive.

No such DSL method 'dockerr' found among steps [...]

Cause: the step name is misspelled, or the plugin that provides the step is not installed (for example, the Pipeline Utility Steps plugin is missing but readJSON is called).

Fix: Check the step in /pipeline-syntax to confirm it exists; use jcli list-plugins to check the plugins.

groovy.lang.MissingPropertyException: No such property: BUILD_NUMBER for class: groovy.lang.Binding

Cause: Writing directly in a Groovy string ${BUILD_NUMBER}. In most cases Jenkins falls back to resolving it via env as a fallback, but inside @NonCPS methods or shared library classes, it does not.

Fix: Always write ${env.BUILD_NUMBER}, or use inside the shell $BUILD_NUMBER.

The Restart from Stage button is grayed out / missing

Cause: a Scripted pipeline; the build is still running; restart is only possible from a top-level stage; or disableRestartFromStage().

Fix: Use Declarative; when you need intermediate artifacts, combine it with preserveStashes().

Command-line tasks
1. Without jenkins-cli, use curl to validate the Jenkinsfile in the current directory.
curl -s -u "admin:$JENKINS_TOKEN" -X POST -F "jenkinsfile=<Jenkinsfile" \
  http://127.0.0.1:8080/pipeline-model-converter/validate
2. In Declarative, store the result of git rev-parse --short HEAD as an environment variable SHORT_SHA.
steps {
  script {
    env.SHORT_SHA = sh(script: 'git rev-parse --short HEAD', returnStdout: true).trim()
  }
  echo "SHORT_SHA=${env.SHORT_SHA}"
}
Scenario analysis
A team wants “one parallel stage per microservice directory, with the number of directories changing as the repository changes.” Should they use Declarative or Scripted?

Keep the overall pipeline in Declarative (for validation, post and visualization); inside one stage's script {} block, first use sh(returnStdout: true) to list the directories, and build def branches = [:], where each element is a closure (which internally calls sh), and finally parallel branches. Note: a closure that references the loop variable must first copy it to a local variable (def svc = it); with many directories, limit concurrency or merge them. If the logic keeps growing, wrap it in a shared-library step (Lesson 5).

Verified instructional videos

▶
What Is the Difference Between Scripted and Declarative Pipeline — CloudBeesTV
English · The two syntaxes: their roles and differences
▶
#5 Jenkins Pipelines | Declarative vs scripted Syntax — Extreme Automation - Kamal Girdher
English · Side-by-side comparison of two ways to write the same flow
▶
How To Restart a Jenkins Pipeline From a Stage — CloudBeesTV
English · How to use Restart from Stage

Official documentation

Video storyboard (about 80 s)

Shot 1 · 0–20s
Visual: split screen, Declarative on the left and Scripted on the right; the same feature is highlighted line by line.
Narration: both styles ultimately run on the same CPS engine.
Shot 2 · 20–45s
Visual: the Declarative file passes through a “model validation” gate; the misspelled step is blocked, and no steps run.
Narration: Declarative validates the structure before running, so errors do not surface halfway through the run.
Shot 3 · 45–65s
Visual: the Replay and Restart from Stage buttons on the build page, each demonstrated separately.
Narration: Replay is for temporary debugging; Restart from Stage resumes from a top-level stage, and it only supports Declarative.
Shot 4 · 65–80s
Visual: the script block is magnified and labeled “escape hatch”, and a long Groovy block is dragged onto the shared library icon.
Narration: the script block is an escape hatch; large chunks of logic should move to a shared library or to a script on the agent.
or score ≥ 70% on the quiz

Module 3 · agent, environment, parameters and when

13:00 – 21:00 · Each stage answers four questions: Where does it run? With which variables and credentials? Which parameters control it? Under which conditions does it run?
8 minDeclarative directivesCredentials gitea-myapp / registry-creds★★★★★
Learning objectives
  • Choose agents for myapp: top-level agent none + stage level label/docker, and understand that each stage with its own agent is allocated an executor separately and performs an implicit checkout.
  • Use environment to define variables, and use credentials() to bind credentials (_USR/_PSW suffix), and avoid leaking secrets through Groovy interpolation.
  • Use parameters with its five types (string/text/booleanParam/choice/password) to parameterize builds, and understand why “parameters only appear after the first run”.
  • Use when with its built-in conditions (branch/tag/buildingTag/changeRequest/changeset/environment/expression/triggeredBy/not/allOf/anyOf) to control stages, and use beforeAgent true to avoid allocating agents for skipped stages.
Prerequisites: The Declarative structure from Module 2. Priority:★★★★★

agent: where it runs

SyntaxMeaningUse in myapp
agent anyAny available nodeNot recommended: it may run on an unsuitable node
agent noneTop level does not allocate; each stage declares its ownTop-level form used in this lesson: waits input does not occupy an executor
agent { label 'linux && docker' }Label expressions (&&,||,!, parentheses)The stage that builds the image (agent1's label linux docker satisfies both)
agent { node { label 'docker'; customWorkspace '/tmp/x' } }Same label; can add customWorkspaceRarely needed
agent { docker { image 'python:3.13-slim'; label 'linux && docker' } }Starts a container on a node that matches the label; steps run inside the containerUnit tests (Module 6 explains the mechanism)
agent { dockerfile { filename 'ci/Dockerfile.test' } }Build an image from the Dockerfile in the repository first, then use it as the agentWhen the toolchain needs customization
agent { kubernetes { yaml '…' } }Kubernetes plugin creates Pods dynamicallyLesson 5

Key point: a stage-level agent will reallocate the executor and workspace, and implicitly perform the checkout again checkout scm (unless skipDefaultCheckout). To share one workspace between two stages, nest them inside a parent stage that has an agent, or use reuseNode true (Module 6).

environment: with which variables

  • Top level environment applies to all stages; a stage-level value overrides the top level; values can reference previously defined variables and built-in variables: IMAGE = "myapp:${APP_VERSION}-${BUILD_NUMBER}".
  • Built-in variables (in the Global Variable Reference: env): BUILD_NUMBER,BUILD_TAG,JOB_NAME,WORKSPACE,NODE_NAME,BUILD_URL; after the Git plugin checks out, there are GIT_COMMIT,GIT_BRANCH; in Multibranch there are BRANCH_NAME,CHANGE_ID etc. (Module 7).
  • credentials('id') Binding by credential type:
Credential typeFOO = credentials('id') Gives
Secret textFOO = text
Username with password (such as gitea-myapp,registry-creds)FOO = username:password,FOO_USR,FOO_PSW
Secret fileFOO = temporary file path
SSH Username with private keyFOO = temporary file path for the private key,FOO_USR, (if there is a passphrase) FOO_PSW

For other types (certificates, cloud credentials), use withCredentials([...]) step. Credential values that appear in logs are replaced with ****, but only reference it in the shell (single quotes) to be safe: sh 'docker login -u "$REG_USR" --password-stdin <<< "$REG_PSW"'.

parameters: which parameters control it

TypeExampleRead as
stringstring(name: 'IMAGE_SUFFIX', defaultValue: '', description: 'Extra tag suffix')params.IMAGE_SUFFIX
textMulti-line textparams.NOTES
booleanParambooleanParam(name: 'PUSH_IMAGE', defaultValue: false, description: 'Push image')params.PUSH_IMAGE (boolean)
choicechoice(name: 'PY', choices: ['3.13', '3.12'])The first option is the default value
passwordPassword entered at run timeNot recommended: prefer credentials

parameters The directive is essentially “at run time, change the job's properties to this.” So: Before the first run the job does not know about the parameters (the first run uses the default values; the parameters appear only afterward Build with Parameters). Parameters added manually in the UI are overwritten by the Jenkinsfile on the next run. Parameter values appear both in params and env ; however, env are all strings (env.PUSH_IMAGE == 'false' ; even “false” is a truthy string!). For boolean checks, use params.

options and triggers

Common options: buildDiscarder(logRotator(numToKeepStr: '20', artifactNumToKeepStr: '5')),timeout(time: 30, unit: 'MINUTES'),timestamps(),disableConcurrentBuilds(abortPrevious: true),skipDefaultCheckout(),skipStagesAfterUnstable(),retry(2),quietPeriod(10),preserveStashes(),parallelsAlwaysFailFast(),durabilityHint(…),disableResume(). triggers: cron('H 2 * * 1-5') (H hashes the minute by job name, to avoid a thundering herd at the top of the hour),pollSCM('H/15 * * * *'),upstream(upstreamProjects: 'lib', threshold: hudson.model.Result.SUCCESS). With a webhook, pollSCM is not needed (Module 7).

when: under which conditions it runs

ConditionExampleNote
branchbranch 'main',branch pattern: 'release/.*', comparator: 'REGEXP'Read BRANCH_NAME, falls back when empty GIT_LOCAL_BRANCH; the official help states “Only works in Multibranch”
buildingTag() / tag 'v*'For tag buildsMultibranch needs Discover tags enabled
changeRequest()changeRequest target: 'main'PR builds (CHANGE_ID exists)
changesetchangeset 'app/**'based on the changeset of this build; the changeset is empty on the first build
environment / equalsenvironment name: 'DEPLOY', value: 'true'String comparison
expressionexpression { params.PUSH_IMAGE }Groovy returns true or false; null is treated as false
triggeredBytriggeredBy 'TimerTrigger',triggeredBy cause: 'UserIdCause'distinguishes scheduled / manual / SCM
not / allOf / anyOfallOf { branch 'main'; expression { params.PUSH_IMAGE } }Can be nested

Evaluation timing: by default, after the stage's agent is allocated is evaluated; skipped stages still waste an executor and pull an image. beforeAgent true Set it to evaluate before allocation; beforeInput true Evaluate before input runs; beforeOptions true Evaluated before the stage options (such as timeout); priority: beforeOptions > beforeInput > beforeAgent. Trade-off: beforeAgent When the stage has not checked out code yet,GIT_COMMIT and similar checkout-produced variables are not available; changeset reads the changeset already recorded for this build, but the changeset is recorded only at the first checkout. For a top-level agent none condition, make sure an earlier stage has already performed a checkout.

When to use which form

  • Branch / PR / tag control → branch/changeRequest/buildingTag (Multibranch).
  • Manual switch → booleanParam + expression.
  • Decide whether to build based on directory → changeset (monorepo).
  • Slow tests you only want to run at night → triggeredBy 'TimerTrigger'.
Common misconceptions① “when { branch 'main' } is available in a regular Pipeline job”—a regular job does not have BRANCH_NAME, so the condition is always false (you will see this in this module's lab). ② “if (env.PUSH_IMAGE) can test a boolean parameter”—a string 'false' is truthy in Groovy. ③ “environment can contain arbitrary Groovy”—it can only be a string/interpolation,credentials() and similar limited forms; for complex computation use script { env.X = … }. ④ “A stage-level agent reuses the workspace contents of the previous stage”—it checks out again; build artifacts must be passed via stash or reuseNode.

Evaluation order of a stage

Stage startsVariable evaluation whenbeforeOptions optionstimeout/retry… whenbeforeInput inputApproval whenbeforeAgent agentAllocate + check out when (default)after agent environmentcredentials binding steps→ post A stage evaluates when in only one of these positions, determined by beforeOptions / beforeInput / beforeAgent; if none of them is set, it is evaluated after agent
Figure 3-1 The position where when is evaluated determines whether a skipped stage wastes an executor (summarized from sections such as “Evaluation order before entering agent” in the Pipeline Syntax documentation)

Agent layout of the myapp pipeline in this lesson

pipeline · agent none · options · parameters · environment Unit testagent docker python:3.13-slimon linux && dockerAlways runs Build imageagent label linux && dockerdocker buildAlways runs Pushwhen beforeAgent:branch main && PUSH_IMAGEcredentials('registry-creds') Nightly slow testswhen triggeredByTimerTrigger(optional extension)
Figure 3-2 Top-level agent none; each stage requests an agent on demand

Interactive: when evaluator

Set the build context and see whether each stage in this lesson's Jenkinsfile runs and whether it is allocated an agent. The rules follow Declarative's actual semantics: branch Read BRANCH_NAME (falls back to when empty GIT_LOCAL_BRANCH), and the boolean value of the parameter comes from params.

Quick reference for common usage

pipeline {
  agent none
  parameters {
    booleanParam(name: 'PUSH_IMAGE', defaultValue: false, description: 'Push image (main only)')
    choice(name: 'LOG_LEVEL', choices: ['INFO', 'DEBUG'], description: 'gunicorn log level')
  }
  environment {
    APP_VERSION = '1.1'
    IMAGE = "myapp:${APP_VERSION}-${BUILD_NUMBER}"
  }
  stages {
    stage('Push') {
      agent { label 'linux && docker' }
      when {
        beforeAgent true
        allOf { branch 'main'; expression { params.PUSH_IMAGE } }
      }
      environment { REG = credentials('registry-creds') }   // REG_USR / REG_PSW
      steps { sh 'echo "$REG_PSW" | docker login localhost:3000 -u "$REG_USR" --password-stdin' }
    }
  }
}
CommandPurpose
jcli build myapp -p PUSH_IMAGE=true -p LOG_LEVEL=DEBUG -s -vBuild with parameters
jcli get-job myapp | grep -A3 ParameterDefinitionConfirm the parameters are written to the job configuration
jcli create-credentials-by-xml system::system::jenkins _ < cred.xmlCreate credentials in the global domain
jcli list-credentials system::system::jenkinsList credential IDs (without showing secrets)
http://127.0.0.1:8080/env-vars.htmlList of built-in environment variables supported by the current instance

How to verify: In Pipeline Graph View, stages skipped by when show as skipped; the console shows Stage "Push" skipped due to when conditional. Common mistakes: Inside environment you write X = sh(...) (it belongs inside script). Production use: The same Jenkinsfile takes different paths for PRs, main, and tags.

Lab 3: Parameterize the myapp pipeline and observe when (about 8 min)

Create registry-creds: in Gitea (http://127.0.0.1:3000/user/settings/applications) for lab generate a token with write:package permission, then:
cd ~/jenkinslab
read -rs REG_TOKEN
cat > registry-creds.xml <<EOF
<com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>
  <scope>GLOBAL</scope>
  <id>registry-creds</id>
  <description>Gitea container registry (lab)</description>
  <username>lab</username>
  <password>${REG_TOKEN}</password>
</com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>
EOF
jcli create-credentials-by-xml system::system::jenkins _ < registry-creds.xml
rm -f registry-creds.xml; unset REG_TOKEN
jcli list-credentials system::system::jenkins | grep -E 'gitea-myapp|registry-creds'

If you already created it in Lesson 1, registry-creds, this step will report that the ID already exists; just skip it.

Rewrite the Jenkinsfile: top level agent none, use a docker agent for unit tests, and add parameters and when:
pipeline {
  agent none
  options {
    buildDiscarder(logRotator(numToKeepStr: '20', artifactNumToKeepStr: '5'))
    timeout(time: 20, unit: 'MINUTES')
    timestamps()
    disableConcurrentBuilds(abortPrevious: true)
  }
  parameters {
    booleanParam(name: 'PUSH_IMAGE', defaultValue: false, description: 'Push image after build (main branch only)')
    choice(name: 'LOG_LEVEL', choices: ['INFO', 'DEBUG'], description: 'Log level for smoke tests')
  }
  environment {
    APP_VERSION = '1.1'
    IMAGE = "myapp:${APP_VERSION}-${BUILD_NUMBER}"
    REGISTRY = 'localhost:3000/lab'
  }
  stages {
    stage('Unit test') {
      agent { docker { image 'python:3.13-slim'; label 'linux && docker' } }
      environment { PIP_DISABLE_PIP_VERSION_CHECK = '1' }
      steps {
        sh '''
          python -m venv .venv
          . .venv/bin/activate
          pip install --no-cache-dir -q -r requirements-dev.txt
          pytest -q
        '''
      }
    }
    stage('Build image') {
      agent { label 'linux && docker' }
      steps { sh 'docker build -t "$IMAGE" .' }
    }
    stage('Push') {
      agent { label 'linux && docker' }
      when {
        beforeAgent true
        allOf { branch 'main'; expression { params.PUSH_IMAGE } }
      }
      environment { REG = credentials('registry-creds') }
      steps {
        sh '''
          echo "$REG_PSW" | docker login localhost:3000 -u "$REG_USR" --password-stdin
          docker tag "$IMAGE" "$REGISTRY/$IMAGE"
          docker push "$REGISTRY/$IMAGE"
          docker logout localhost:3000
        '''
      }
    }
  }
  post {
    always { echo "Result: ${currentBuild.currentResult}; PUSH_IMAGE=${params.PUSH_IMAGE}" }
  }
}

For unit tests, use a venv and disable the pip cache: Docker Pipeline runs the container as the agent's uid (1000), and that user does not exist in the image,HOME unset, so /, installing directly pip install --user will fail with a permission error (see the Module 6 troubleshooting section).

Commit and run twice (the first run makes the parameters take effect; the second run uses them):
cd ~/jenkinslab/myapp
jcli declarative-linter < Jenkinsfile && git commit -am "Lesson 2: agent none + parameters + when" && git push
jcli build myapp -s | tail -n 1
jcli build myapp -p PUSH_IMAGE=true -s -v | grep -E 'Stage "Push"|Finished'
Completed myapp #3 : SUCCESS
Stage "Push" skipped due to when conditional
Finished: SUCCESS

Even though PUSH_IMAGE=true, Push is still skipped: myapp is a regular Pipeline job, with no BRANCH_NAME, and no “checkout to local branch” is configured,GIT_LOCAL_BRANCH is empty,branch 'main' is false. It will take effect in Module 7 when switched to Multibranch.

Verify the effect of beforeAgent: in Pipeline Graph View, open the second build; the Push stage shows as skipped, and the console shows no Running on agent1 for it. Temporarily remove beforeAgent true and run it again with Replay to compare the extra agent allocation and checkout.
Verify the parameter type trap: use Replay to add a stage before the Push stage:
stage('param types') {
  steps {
    echo "params.PUSH_IMAGE type: ${params.PUSH_IMAGE.getClass().simpleName}"
    echo "env.PUSH_IMAGE value: '${env.PUSH_IMAGE}'"
  }
}
params.PUSH_IMAGE type: Boolean
env.PUSH_IMAGE value: 'false'

If the sandbox rejects getClass, change it to echo "${params.PUSH_IMAGE instanceof Boolean}".

Case 1: every PR occupies a deploy agent

Problem: The agent for the “Deploy” stage is label 'deploy',when { branch 'main' } without beforeAgent. Although PR builds ultimately skip deployment, they first queue for the scarce deploy agent, making PR feedback 10 minutes slower. Approach: Add beforeAgent true. Limitation: With beforeAgent, you cannot depend on variables that exist only after checkout.

Case 2: a boolean parameter is always true

Problem:when { environment name: 'DRY_RUN', value: 'true' } Works fine, but script { if (env.DRY_RUN) { … } } always takes the dry-run branch. Approach: Change it to if (params.DRY_RUN). Limitation: On scheduled triggers the parameters take their default values, so the default should be the “safe” side (for example PUSH_IMAGE=false).

Case 3: a secret appears in the build log

Problem:sh "echo ${REG_PSW} | docker login …", Jenkins prints a Groovy interpolation warning; because set -x, some transformed values were not masked. Approach: Use single quotes consistently + --password-stdin; in code review, treat double quotes containing credential variables as a blocking issue (Module 8 checklist). Limitation: Anyone who can modify the Jenkinsfile can read the credentials bound to the build; credential isolation relies on folder-scoped credentials and branch protection (Lesson 6).

Common errors and fixes

There are no nodes with the label ‘linux&&docker’ (the build stays queued)

Cause: Label spelling or expression is wrong; agent1 is offline; the Built-In Node was set to 0 executors and there are no other nodes.

jcli get-node agent1 | grep -E 'label|numExecutors'

Fix: Confirm that the agent1 label is linux docker (space-separated), and write the expression as 'linux && docker'. Lesson 7 explains queuing causes in detail.

ERROR: registry-creds (Could not find credentials entry with ID 'registry-creds')

Cause: The credential ID is misspelled, or the credential is stored in another folder domain that the current job cannot see.

Fix:jcli list-credentials system::system::jenkins Check it; in Multibranch, watch for folder-level credentials (Module 7).

Warning: A secret was passed to "sh" using Groovy String interpolation, which is insecure.

Cause: A credential variable is referenced inside a double-quoted string.

Fix: Switch to single quotes so the shell expands it.

Parameters changed, but the Build with Parameters page did not update

Cause: The parameters directive updates job properties only at run time.

Fix: Run it once (or use Replay); do not maintain parameters manually in the UI.

Stage "Push" skipped due to when conditional (even though it is the main branch)

Cause: A regular Pipeline job has no BRANCH_NAME; or in Multibranch, the branch name is actually master.

Fix: Use Multibranch; or in a regular job, switch to expression { env.GIT_BRANCH == 'origin/main' } (note that beforeAgent runs before checkout, so GIT_BRANCH is unavailable).

Command-line tasks
1. Write a stage condition that runs only for tag builds and only when triggered manually.
when {
  beforeAgent true
  allOf { buildingTag(); triggeredBy cause: 'UserIdCause' }
}
2. Use jenkins-cli with PUSH_IMAGE=true,LOG_LEVEL=DEBUG to run myapp and wait for it to finish.
jcli build myapp -p PUSH_IMAGE=true -p LOG_LEVEL=DEBUG -s
Scenario analysis
The monorepo has services/api and services/web, you want to build only the services that changed, and PR builds should not push images. How do you design the when conditions?

One stage per service: when { beforeAgent true; changeset 'services/api/**' }; push stage: when { beforeAgent true; allOf { branch 'main'; not { changeRequest() } } }. These stages must come after a stage that has already checked out code (such as Unit test); otherwise the changeset has not been recorded yet at beforeAgent time. Note the limitation of changeset: on a branch's first build or after a force push the changeset may be empty, so you need a “build everything” fallback (for example anyOf { changeset …; triggeredBy 'TimerTrigger' } a nightly full build).

Verified instructional videos

▶
#15 Jenkins Pipelines | Parameters — Extreme Automation - Kamal Girdher
English · How to use Declarative parameters
▶
Jenkins Conditional Stages Explained | Declarative Pipeline Tutorial with Live Examples — Maximum Automation
English · when condition demo
▶
The Correct Way to Handle Credentials in a Jenkins Pipeline — CloudBeesTV
English · Credential binding and interpolation risks

Official documentation

Video storyboard (about 90 s)

Shot 1 · 0–25s
Visual: a stage card passes through four gates in turn: agent, environment, parameters, when.
Narration: every stage must answer four questions: where it runs, which variables it carries, which parameters control it, and which conditions must be met before it runs.
Shot 2 · 25–50s
Visual: the when gate is placed before and after agent; the after version first occupies an executor and is then rejected.
Narration: by default, when is evaluated after the agent is allocated; adding beforeAgent avoids wasting an executor.
Shot 3 · 50–70s
Visual: credentials('registry-creds') expands into REG_USR and REG_PSW; a red warning appears in the log of the double-quoted version.
Narration: username/password credentials generate two suffixed variables; reference them with single quotes and let the shell expand them.
Shot 4 · 70–90s
Visual: a regular Pipeline job and a Multibranch job side by side; in the former BRANCH_NAME is empty and the branch condition is false.
Narration: the branch condition depends on the branch name provided by Multibranch.
or score ≥ 70% on the quiz

Module 4 · Parallel, matrix and stage control

21:00 – 28:00 · Parallelize independent checks, use matrix to cover multiple Python versions, then use failFast, catchError, retry and timeout to make failures “fast, accurate and not masked”
7 minparallel · matrix★★★★☆
Learning objectives
  • Write the Declarative parallel and matrix (axes/axis/excludes/ cell level agent), and know that axis variables appear as environment variables inside a cell.
  • Use failFast true / parallelsAlwaysFailFast() to control how failures propagate across parallel branches.
  • Use catchError,warnError,unstable,error to precisely set the stage and build results; use retry (including conditions: [agent()]) and timeout (including activity: true) to handle flakiness.
  • Understand the real cost of parallelism: every branch with an agent needs an executor; at the Groovy level, parallelism is interleaved.
Prerequisites: The agent and when from Module 3. Priority:★★★★☆

What: parallel and matrix

stage('Static checks') {
  failFast true
  parallel {
    stage('Python syntax') {
      agent { docker { image 'python:3.13-slim'; label 'linux && docker' } }
      steps { sh 'python -m compileall -q .' }
    }
    stage('Dockerfile lint') {
      agent { label 'linux && docker' }
      steps {
        warnError('hadolint has warnings') {
          sh 'docker run --rm -i hadolint/hadolint < Dockerfile'
        }
      }
    }
  }
}
stage('Test matrix') {
  matrix {
    axes {
      axis { name 'PY'; values '3.12', '3.13' }
    }
    agent {
      docker { image "python:${PY}-slim"; label 'linux && docker' }
    }
    stages {
      stage('pytest') {
        steps { sh 'echo "Python $PY"; python --version' }
      }
    }
  }
}

parallel: several sub-stages listed inside one stage run at the same time; each sub-stage can have its own agent, when and post. matrix: declare several axes; Jenkins generates all combinations (cells), and each cell runs the stages inside matrix in order stages, with cells running in parallel. Directives available inside a cell: agent,environment,input,options,post,tools,when; axis values are available as environment variables ($PY / ${PY}).

excludes: remove unneeded combinations

matrix {
  axes {
    axis { name 'PLATFORM'; values 'linux', 'windows', 'mac' }
    axis { name 'BROWSER';  values 'firefox', 'chrome', 'safari', 'edge' }
  }
  excludes {
    exclude {
      axis { name 'PLATFORM'; values 'linux' }
      axis { name 'BROWSER';  values 'safari' }
    }
    exclude {
      axis { name 'PLATFORM'; notValues 'windows' }
      axis { name 'BROWSER';  values 'edge' }
    }
  }
  …
}

12 combinations, minus linux×safari and (non-windows)×edge, leaves 9. notValues means “all values except these”. This example follows the approach in the official Pipeline Syntax documentation.

Why: parallelism and failure control

  • Feedback time: lint, unit tests and image builds run in parallel when they do not depend on each other; the total duration is determined by the slowest branch.
  • Coverage: matrix uses one definition to cover multiple runtime versions, avoiding copy-pasted stages.
  • Failure semantics: by default, a failing parallel branch does not interrupt the other branches (so you see all failures); failFast true then aborts the remaining branches at the first failure (saving executors).

How: toolbox for controlling stage results

Step / optionEffectTypical use
catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') { … }Catches errors, sets the build and stage result according to the parameters, and continues with subsequent stagesWhen a non-critical check fails, the stage is marked red but the build stays green (results can only get worse, never better)
warnError('msg') { … }Equivalent to catchError with both set to UNSTABLELint warnings
unstable('msg')Sets the build and stage to UNSTABLECoverage below threshold
error('msg')Fails immediately (no stack trace printed)Precondition not met
retry(3) { … } / retry(count: 2, conditions: [agent(), nonresumable()]) { … }Retry block; agent() with conditions so it retries only on “suspected infrastructure” failures (such as an agent disconnect), and can switch to another agentnetwork jitter, temporary agents
timeout(time: 10, unit: 'MINUTES') { … } / timeout(time: 3, unit: 'MINUTES', activity: true)Absolute timeout / no-output timeoutHung tests
options { skipStagesAfterUnstable() }Build becomes UNSTABLE and subsequent stages are skippedDo not push images when tests are flaky
options { parallelsAlwaysFailFast() }Parallel/matrix blocks default to failFastEnvironments with scarce executors

The real cost of parallelism

  • Every parallel branch with an agent needs one executor. When agent1 has only 2 executors, 2 of the 4 branches wait in the queue (log: Waiting for next available executor on ‘agent1’)—“parallel” becomes two batches.
  • Parallel branches on the same node each get a separate workspace (myapp,myapp@2), so they do not overwrite each other, but it also means each one checks out separately.
  • The CPS VM is single-threaded per build: the Groovy in parallel branches is interleaved, and only sh and other external processes actually run in parallel.
  • Too many matrix combinations make the generated code too large (you may hit Method code too large and similar compile limits), and overwhelm the executor pool. Keep the combinations to single digits up to a dozen or so, and trim them with excludes.

When

  • Independent checks that each take over 30 seconds → parallel.
  • The same set of steps × multiple versions/platforms → matrix.
  • Executors are scarce → failFast or fewer branches; do not parallelize 10-second steps too (the overhead of allocating an agent and checking out may be larger).
Common misconceptions① “Parallel is always faster”—if there are not enough executors, branches just queue. ② “catchError turns a failure into success”—it can only keep the result the same or make it worse,buildResult: 'SUCCESS' means “do not make the build worse because of this error”. ③ “Matrix cells share a workspace”—each cell gets its own agent and workspace. ④ “retry fixes flaky tests”—it only hides the problem; flaky tests should be fixed; retry is better suited to infrastructure failures.

Execution topology of this lesson's pipeline

Start Static checks (parallel, failFast) Python syntaxdocker python:3.13-slim Dockerfile linthadolint · warnErrorWarning → UNSTABLE Test matrix (PY axis) PY = 3.12venv · pytest · junit PY = 3.13venv · pytest · junit Build imageskipStagesAfterUnstableis skipped when
Figure 4-1 Two parallel blocks in series: quick static checks first, then the version matrix, and finally the image build

Result combination rules

SUCCESS UNSTABLE FAILURE ABORTED The build result can only get worse along the direction of the arrows; catchError's buildResult can only limit how far it gets worse
Figure 4-2 Monotonicity of currentBuild.result

Interactive: parallel timeline

Adjust the executor count, failFast, whether to exclude 3.12, and whether the 3.13 tests fail, then click “Run”. Each cell represents 1 second; gray means waiting in the queue for an executor.

Syntax quick reference

SyntaxDescription
stage('x') { failFast true; parallel { stage('a'){…} stage('b'){…} } }Parallel + fail fast
matrix { axes { axis { name 'PY'; values '3.12','3.13' } } stages { … } }Matrix
excludes { exclude { axis { name 'PY'; values '3.12' } } }Exclude combinations
script { def b = [:]; ['a','b'].each { n -> b[n] = { sh "echo ${n}" } }; parallel b }Dynamic parallel (Scripted style)
catchError(buildResult: 'SUCCESS', stageResult: 'UNSTABLE') { sh 'exit 1' }stage yellow, build unaffected
retry(count: 2, conditions: [agent()]) { node('linux') { … } }retry on a different node when the agent disconnects (the condition requires the block to contain node)
timeout(time: 3, unit: 'MINUTES', activity: true) { sh 'pytest' }abort if there is no log output for 3 minutes
# observe each parallel branch's workspace (run while the build is running)
docker compose exec agent1 sh -c 'ls -d /home/jenkins/agent/workspace/myapp*'
/home/jenkins/agent/workspace/myapp
/home/jenkins/agent/workspace/myapp@2
/home/jenkins/agent/workspace/myapp@2@tmp
/home/jenkins/agent/workspace/myapp@tmp

How to verify: In Pipeline Graph View, parallel branches are shown side by side, and matrix cells are shown as Matrix - PY = '3.12'. Common mistakes: Nesting parallel or matrix inside a parallel sub-stage (Declarative does not allow it; validation reports an error). Production use: Multi-version compatibility testing and cross-platform builds.

Lab 4: parallel static checks + Python version matrix (about 7 min)

In the Jenkinsfile, replace the stage('Unit test') entire block with the two stages below, and in options add skipStagesAfterUnstable():
    stage('Static checks') {
      failFast true
      parallel {
        stage('Python syntax') {
          agent { docker { image 'python:3.13-slim'; label 'linux && docker' } }
          steps { sh 'python -m compileall -q -x "/\\.venv/" .' }
        }
        stage('Dockerfile lint') {
          agent { label 'linux && docker' }
          steps {
            warnError('hadolint reported issues') {
              sh 'docker run --rm -i hadolint/hadolint < Dockerfile'
            }
          }
        }
      }
    }
    stage('Test matrix') {
      matrix {
        axes {
          axis { name 'PY'; values '3.12', '3.13' }
        }
        agent { docker { image "python:${PY}-slim"; label 'linux && docker' } }
        stages {
          stage('pytest') {
            options { timeout(time: 5, unit: 'MINUTES', activity: true) }
            steps {
              sh '''
                python -m venv .venv
                . .venv/bin/activate
                pip install --no-cache-dir -q -r requirements-dev.txt
                mkdir -p reports
                pytest -q --junitxml="reports/junit-py$PY.xml"
              '''
            }
          }
        }
      }
    }

-x "/\\.venv/": in a Groovy single-quoted string, the \\ is a backslash, and the shell receives /\.venv/, so compileall skips the venv.

Validate, commit, build:
cd ~/jenkinslab/myapp
jcli declarative-linter < Jenkinsfile && git commit -am "Lesson 2: parallel + matrix" && git push
jcli build myapp -s -v | grep -E '^\[Pipeline\] \{ \(|Finished|hadolint|DL[0-9]{4}'
[Pipeline] { (Declarative: Checkout SCM)
[Pipeline] { (Static checks)
[Pipeline] { (Branch: Python syntax)
[Pipeline] { (Branch: Dockerfile lint)
-:5 DL3013 warning: Pin versions in pip. …
[Pipeline] { (Test matrix)
[Pipeline] { (Branch: Matrix - PY = '3.12')
[Pipeline] { (Branch: Matrix - PY = '3.13')
[Pipeline] { (Build image)
Finished: UNSTABLE

If hadolint reports issues, the build becomes UNSTABLE, and because skipStagesAfterUnstable(), the Build image stage after it is skipped. This is exactly why warnings should not be quietly ignored. With no warnings in your Dockerfile, the build is SUCCESS.

Decide on the warning policy: if the team believes hadolint warnings should not block building the image, change warnError to catchError(buildResult: 'SUCCESS', stageResult: 'UNSTABLE'): the stage shows yellow and the build result is unaffected. Commit and compare the results of the two builds.
Observe executor queuing: in Manage Jenkins → Nodes → agent1, temporarily set the executor count to 1, build again, and the console will show Waiting for next available executor on ‘agent1’, and the two matrix cells run one after another. Change the value back after the lab.

Case 1: matrix saturates the executor pool

Problem: A library's tests used 4 JDKs × 3 operating systems × 2 databases = 24 cells; every PR filled the agent pool, and other teams' builds queued for 40 minutes. Approach: PRs run only one cell, “latest JDK × linux × postgres” (when { not { changeRequest() } } placed at the cell level), with the full matrix running after merge to main and nightly; add failFast true. Limitation: A cell-level when still generates the cells; they are just skipped, so the visualization will show many skipped cells.

Case 2: parallel branches delete each other's files

Problem: A Scripted pipeline, in the same node block, uses parallel to start two sh, both in the same workspace rm -rf build/. Approach: Have each branch node {} (get its own workspace), or use dir('build-a') to isolate them. Limitation: Parallel branches within the same node block share a workspace; this is a common pitfall.

Case 3: retry hides a real race condition

Problem: Integration tests failed intermittently, so the team added retry(3), and a real data race bug made it to production. Approach: Retry only on infrastructure failures: retry(count: 2, conditions: [agent()]); if tests fail, publish the junit report and keep the failure, and open a separate ticket to fix the flaky tests. Limitation:agent() The condition only recognizes cases such as agent disconnects; network timeouts and similar cases still require human judgment.

Common errors and fixes

WorkflowScript: …: Parallel stages or branches can only be included in a top-level stage.

Cause: A parallel was nested inside a parallel sub-stage (or nested inside a matrix).

Fix: Flatten the structure, or change the inner parallel to script { parallel … }. Exact wording depends on your plugin version.

Waiting for next available executor on ‘agent1’

Cause: The number of parallel branches > the number of idle executors.

Fix: Add agents / executors, reduce the number of branches, or accept queuing; Lesson 5 uses Kubernetes dynamic agents to scale elastically.

In matrix, ${PY} is null; the agent image name becomes python:null-slim

Cause: An axis variable was referenced outside the matrix (such as in the top-level environment), or the axis name was misspelled.

Fix: Axis variables are only available inside a cell (agent, environment, stages).

Timeout has been exceeded / Cancelling nested steps due to timeout

Cause: The timeout has taken effect and is aborting the steps inside the block.

Fix: Confirm it is really stuck (check the last output), and distinguish absolute timeout from activity: true; if the test is just slow, adjust the threshold or split the tests.

Build is UNSTABLE, and the later stages show skipped

Cause:skipStagesAfterUnstable() is in effect (for example, warnError or test failures turned the build yellow).

Fix: This is expected behavior; if a check should not affect the build, use catchError(buildResult: 'SUCCESS', …).

Command-line tasks
1. Write a matrix: axes PY (3.12, 3.13) × DB (sqlite, redis), excluding 3.12 × redis.
matrix {
  axes {
    axis { name 'PY'; values '3.12', '3.13' }
    axis { name 'DB'; values 'sqlite', 'redis' }
  }
  excludes {
    exclude {
      axis { name 'PY'; values '3.12' }
      axis { name 'DB'; values 'redis' }
    }
  }
  stages { stage('t') { steps { echo "PY=${PY} DB=${DB}" } } }
}
2. Make a stage abort when it has no log output for 2 minutes, and on failure only mark the stage red while the build keeps its original result.
steps {
  catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
    timeout(time: 2, unit: 'MINUTES', activity: true) {
      sh './slow-check.sh'
    }
  }
}
Scenario analysis
The agent pool has only 4 executors, the pipeline has 6 parallel branches averaging 3 minutes each, and 2 of them take only 15 seconds. How would you optimize?

Merge the two 15-second branches into one branch or run them serially in a previous stage (the overhead of allocating an agent and checking out may be longer than the steps themselves); the remaining 4 branches exactly match the executor count. If the remaining results are meaningless after one branch fails (such as a compile failure), add failFast true. In the long run, use Kubernetes dynamic agents (Lesson 5) to scale on demand, and use disableConcurrentBuilds(abortPrevious: true) to abort old builds when a new commit arrives on the same branch.

Verified instructional videos

▶
Simplifying Parallel Pipeline Creation in Jenkins — CloudBeesTV
English · How to write parallel stages
▶
#11 Jenkins Pipelines | Parallel stages — Extreme Automation - Kamal Girdher
English · Declarative parallel demo

Declarative matrix dedicated video: No verified video found; refer to the official documentation and this module's animations.

Official documentation

Video storyboard (about 80 s)

Shot 1 · 0–20s
Visual: two horizontal progress bars advance at the same time, labeled Python syntax and Dockerfile lint.
Narration: independent checks run at the same time with parallel; the total time depends on the slowest branch.
Shot 2 · 20–45s
Visual: the axes table expands into a grid, and one cell is crossed out by exclude.
Narration: matrix generates all combinations from the axes, excludes removes unneeded combinations, and axis values are environment variables inside a cell.
Shot 3 · 45–65s
Visual: the executor has only two slots, and the third and fourth branches turn gray and wait in the queue.
Narration: every branch with an agent needs an executor; when there are not enough, parallel work turns into queuing.
Shot 4 · 65–80s
Visual: the result bar goes from green to yellow to red; catchError can only stop the arrow of “getting worse”.
Narration: build results can only get worse; catchError and warnError determine how far an error can push the result.
or score ≥ 70% on the quiz

Module 5 · Artifacts, stash and workspace management

28:00 – 35:00 · The workspace lives on the agent, stash lives within this build, and artifacts are kept long-term on the controller — the three have different lifecycles, and using them wrongly leads to “file not found” or “disk full”
7 minjunit · archiveArtifacts · stashws-cleanup 0.49★★★★☆
Learning objectives
  • Describe the workspace (workspace),@2/@tmp directories, stash, archived artifacts, and fingerprints: where each is stored and when it is deleted.
  • Use stash/unstash to pass between different agents / containers small files, and know that by default it is discarded when the build ends,preserveStashes() kept only for Restart from Stage.
  • Use junit to publish test reports,archiveArtifacts (including fingerprint,allowEmptyArchive) to archive artifacts,buildDiscarder to control how much is retained.
  • Use cleanWs() / deleteDir() to manage the workspace, avoiding agent disk exhaustion and false success caused by “leftovers from the last build”.
Prerequisites: The matrix from Module 4 (each cell has its own workspace). Priority:★★★★☆

What: four “destinations for files”

LocationLifecycleSuitable forNot suitable for
Workspaceagent: <Remote root>/workspace/<job>; when concurrent, @2,@3; temp files live in @tmpare kept by default after the build ends, and reused in the next build (incremental checkout)Intermediate files during the buildPassing across agents; serving as a trusted “clean environment”
stashcontroller: under the build directory (as archives)Discarded when this build ends; preserveStashes(buildCount: N) Keeps the stash of the most recent N completed builds, for Restart from StagePassing small files between different stages / agents / containers within the same build (official docs: designed for small files; for files in the 5–100 MB range, consider alternatives)Large files, image tarballs, dependency caches
Archived artifactscontroller: jobs/<job>/builds/<n>/archive/ (can be replaced with an external artifact manager)Kept with the build record, cleaned up by buildDiscarder 's artifactNumToKeepStr/numToKeepStr cleanupReports, manifests, small release packages, image digestsLarge binaries (should be published to an artifact repository / image registry)
Fingerprintscontroller: $JENKINS_HOME/fingerprints/ (MD5)independent of build recordsTracks “which build produced/used this file”—

Why: why not just use the workspace directly?

  • Stage-level agents, matrix cells and docker agents may land on different nodes or different workspaces, so files from the previous stage may not exist in the next stage.
  • Workspace is not cleaned by default: files left by the last build reports/ can make this build junit read old reports and create a “false success”.
  • The controller's JENKINS_HOME disk is expensive: stashes and artifacts are both written here, and large files slow backups and can exhaust the disk.

How: key steps

StepKey parametersDescription
stash name: 'x', includes: 'reports/**', excludes: '…'allowEmpty (default false; an empty stash raises an error),useDefaultExcludes (default true, excludes .git etc.)Ant-style patterns; a stash with the same name overwrites
unstash 'x'—Unpacks into the current directory (affected by dir() )
archiveArtifacts artifacts: 'reports/**', fingerprint: true, allowEmptyArchive: falseexcludes,onlyIfSuccessfulFails by default when the pattern matches nothing (to prevent silent omissions)
junit testResults: 'reports/*.xml', allowEmptyResults: falseskipPublishingChecks etc.When there are failing test cases, the build is set to UNSTABLE; an error is raised if the report file is older than the build start time (to prevent stale reports)
cleanWs() (Workspace Cleanup)deleteDirs,patterns,cleanWhenFailure etc.usually placed in post { cleanup { … } }
deleteDir() (built-in)—Recursively deletes the current directory (used with dir('x') to delete subdirectories)
options { buildDiscarder(logRotator(numToKeepStr: '20', artifactNumToKeepStr: '5')) }daysToKeepStr etc.Keeps the 20 most recent builds, of which only the 5 most recent keep artifacts

Two failure semantics of junit

pytest exits with a non-zero code when there are failing cases → sh failure → stage FAILURE. Put junit inside post { always { … } } , the report is still published, and the final result is FAILURE. If you want “test failure = UNSTABLE (yellow)”, have the test command not exit with a failure code (for example pytest … || true) and let junit set the build to UNSTABLE based on the report — but this needs to be paired with skipStagesAfterUnstable(), otherwise the yellow build will still push images. This lesson takes the former approach: a test failure is a failure.

When

  • Passing files under a few MB across agents / containers within the same build → stash.
  • Outputs that people need to download or audit → archiveArtifacts (small) or publish to an artifact repository (large).
  • Images → push to an image registry; what gets archived is only metadata such as the digest / SBOM.
  • Dependency caches (pip, npm) → a cache volume on the agent or image-layer caching; do not stash them.
Common misconceptions① “A stash can be unstashed in the next build”—by default it is discarded when the build ends; for cross-build use, use artifacts or the Copy Artifact plugin. ② “The workspace is always clean each time”—by default it is reused. ③ “archiveArtifacts is cheap”—all artifacts live on the controller disk, affecting backups and upgrades. ④ “A junit failure makes the stage red”—junit only makes the build UNSTABLE; red comes from the test command's non-zero exit.

How files flow within one build

agent1 (workspace, kept after the build) myapp@2cell PY=3.12reports/junit-py3.12.xml myapp@3cell PY=3.13reports/junit-py3.13.xml myapp (Reports stage)unstash two reports → generate summary.txt and image-id.txtpost cleanup → cleanWs() controller (JENKINS_HOME) stashes/reports-py3.12 / py3.13Deleted when the build ends junit resultstest trends, failing casesKept with the build record builds/N/archive/reports/**, image-id.txtCleaned up by buildDiscarder fingerprints/MD5 → the build that produced/used itfingerprint: true stash unstash junit (each cell) archive
Figure 5-1 Stashes pass through the controller; artifacts and fingerprints stay on the controller long-term; the workspace stays on the agent

Interactive: where did the file go?

Click the events in order and watch the files in each storage area; try unstash after “build end”, or start the next build without cleaning the workspace.

Commands and checks

CommandPurpose
docker compose exec jenkins ls /var/jenkins_home/jobs/myapp/builds/7/archive/reportsSee where archived artifacts are located on the controller
curl -su admin:$JENKINS_TOKEN http://127.0.0.1:8080/job/myapp/lastSuccessfulBuild/artifact/reports/summary.txtDownload the artifacts of the latest successful build
curl -su admin:$JENKINS_TOKEN 'http://127.0.0.1:8080/job/myapp/lastBuild/testReport/api/json?tree=passCount,failCount,skipCount'Read test result statistics
docker compose exec agent1 du -sh /home/jenkins/agent/workspace/*Check agent workspace usage
docker compose exec jenkins du -sh /var/jenkins_home/jobs/*/buildsCheck build record usage
curl -su "admin:$JENKINS_TOKEN" \
  'http://127.0.0.1:8080/job/myapp/lastBuild/testReport/api/json?tree=passCount,failCount,skipCount'
{"_class":"hudson.tasks.junit.TestResult","failCount":0,"passCount":6,"skipCount":0}

How to verify: The build page shows “Test Result” and “Build Artifacts” links; the test badge in Pipeline Graph View shows the number of test cases. Common mistakes:includes written as a path relative to another directory; unstash outside dir() . Production use: Keep SBOMs, test reports and image digests as auditable build outputs.

Lab 5: test reports, stash aggregation and archiving (about 7 min)

In the matrix's stage('pytest') add post (placed steps after):
            post {
              always {
                junit testResults: "reports/junit-py${PY}.xml", allowEmptyResults: false
                stash name: "reports-py${PY}", includes: 'reports/*.xml', allowEmpty: true
              }
            }

allowEmpty: true Used with stash: if pytest crashes before the report is generated, the stash should not create a second error that masks the first; junit's allowEmptyResults: false will clearly report “no reports”.

Replace stage('Build image') with the two stages below, and at the top level options add preserveStashes(buildCount: 3):
    stage('Build image') {
      agent { label 'linux && docker' }
      steps {
        sh '''
          docker build -t "$IMAGE" .
          mkdir -p meta
          docker image inspect --format '{{.Id}}' "$IMAGE" > meta/image-id.txt
        '''
        stash name: 'meta', includes: 'meta/*'
      }
    }
    stage('Reports') {
      agent { label 'linux && docker' }
      options { skipDefaultCheckout() }
      steps {
        unstash 'reports-py3.12'
        unstash 'reports-py3.13'
        unstash 'meta'
        sh '''
          {
            echo "image: $IMAGE"
            echo "id:    $(cat meta/image-id.txt)"
            for f in reports/*.xml; do
              printf '%s tests=%s failures=%s\n' "$f" \
                "$(grep -o 'tests="[0-9]*"' "$f" | head -1 | tr -dc 0-9)" \
                "$(grep -o 'failures="[0-9]*"' "$f" | head -1 | tr -dc 0-9)"
            done
          } > reports/summary.txt
          cat reports/summary.txt
        '''
        archiveArtifacts artifacts: 'reports/**, meta/image-id.txt', fingerprint: true
      }
      post { cleanup { cleanWs() } }
    }

The Reports stage uses skipDefaultCheckout(): it only needs the files from the stash, not the source code; combine it with cleanWs() to ensure it never reads leftovers from the previous build.

Commit and build, then check the artifacts:
cd ~/jenkinslab/myapp
jcli declarative-linter < Jenkinsfile && git commit -am "Lesson 2: junit + stash + archive" && git push
jcli build myapp -s | tail -n 1
curl -su "admin:$JENKINS_TOKEN" http://127.0.0.1:8080/job/myapp/lastBuild/artifact/reports/summary.txt
Completed myapp #6 : SUCCESS
image: myapp:1.1-6
id:    sha256:5c0d…
reports/junit-py3.12.xml tests=6 failures=0
reports/junit-py3.13.xml tests=6 failures=0

If the hadolint warnings from Module 4 make the build UNSTABLE and skip later stages, first adjust the warning policy following step 3 of the Module 4 lab.

Verify the stash lifecycle: on the build page, use Restart from Stage → Reports, because there is preserveStashes(buildCount: 3), unstash succeeds; then use Replay to delete preserveStashes run once, then on this build, use Restart from Stage → Reports, and you will see No such saved stash ‘reports-py3.12’.
Check for leftovers in the workspace:
docker compose exec agent1 sh -c 'du -sh /home/jenkins/agent/workspace/myapp*'

The workspace of the matrix cell still contains .venv (tens of MB). Consider whether you should also add cleanWs()? (Trade-off: keeping it speeds up the next pip install, but accumulates disk usage; in production, a cache volume is usually used instead of a dirty workspace.)

Case 1: JENKINS_HOME grew by 400 GB in one week

Problem: A pipeline archiveArtifacts 'build/**' archived Docker image tar files and node_modules together, with no buildDiscarder. Approach: Push images to a registry and archive only the digest; buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '5')); in Manage Jenkins, set a global build discard policy for jobs that are not configured. Limitation: Old artifacts that have already accumulated need a one-time cleanup (disk investigation in Lesson 7).

Case 2: the tests “passed”, but not a single test case ran

Problem: The test command did not generate a report because of a wrong path, but the workspace contained a three-day-old junit XML, so the build stayed green. Approach: Before each build, rm -rf reports or cleanWs(); junit by default, reports older than the build start time raise an error; do not disable this check just to make the error go away. Limitation: The speed benefit of reusing the workspace must be weighed against trustworthiness.

Case 3: stash saturates the controller's network

Problem: The pipeline stashed 2 GB of build output for 4 parallel test branches to unstash, so each build transferred 10 GB through the controller. Approach: Upload the output to object storage / an artifact repository, and let each branch download it; or run the tests on the same node using reuseNode. Limitation: The official documentation states that stash is intended for small files.

Common errors and fixes

No such saved stash ‘reports-py3.12’

Cause: The stash name is spelled inconsistently (axis variable interpolation), the stage that creates the stash was skipped or failed, unstash was called in another build, or preserveStashes was not used during Restart from Stage.

Fix: Verify the name; on the producing side, use post { always { stash … } }; when a restart is needed, add preserveStashes().

ERROR: No files included in stash ‘meta’

Cause:includes No files matched (the path is relative to the current directory).

Fix:sh 'ls -R meta' Verify; if necessary, allowEmpty: true.

ERROR: No artifacts found that match the file pattern "reports/**". Configuration error?

Cause: There are no matching files in the current workspace (for example, you forgot to unstash, or the files are on a different agent).

Fix: Archive in the workspace where the files were generated, or unstash first; only add it when the set can genuinely be empty allowEmptyArchive: true.

Test reports were found but none of them are new. Did leafNodes run?

Cause: junit read a report older than this build's start time — the tests did not actually run.

Fix: Fix the test command; clean before the build reports/.

agent1 disk full: No space left on device
docker compose exec agent1 df -h /home/jenkins/agent
docker system df

Cause: Workspaces (including venv) and Docker images / build caches have accumulated.

Fix:cleanWs(); regularly docker image prune,docker builder prune (note that this affects caches used by other builds); in post cleanup, delete this build's temporary images.

Command-line tasks
1. Archive dist/*.whl and record fingerprints, and archive only when the build succeeds.
archiveArtifacts artifacts: 'dist/*.whl', fingerprint: true, onlyIfSuccessful: true
2. Use the REST API to download the artifact of the latest successful myapp build meta/image-id.txt.
curl -su "admin:$JENKINS_TOKEN" \
  http://127.0.0.1:8080/job/myapp/lastSuccessfulBuild/artifact/meta/image-id.txt
Scenario analysis
The front-end build artifact is 300 MB and must be used by 3 parallel E2E test branches, after which the deploy stage publishes it. How would you design the file handoff?

300 MB is not suitable for stash (every branch would download it from the controller, which puts heavy disk and network pressure on the controller). Option A: the build stage packages the artifact and uploads it to an artifact repository or object storage (tagged with the build number); the test and deploy stages download it. Option B: build an image, push it to an image registry, and have the test branches run that image directly (closest to deployment). Option C: if everything runs on one node, nested stages + reuseNode a shared workspace can be used, but it loses distributed scaling. Only archive the digest / manifest as a Jenkins artifact.

Verified teaching videos

▶
What Is stash and unstash in Jenkins? — CloudBeesTV
English · Purpose and limits of stash/unstash
▶
Where Does Jenkins Store Archived Artifacts? — CloudBeesTV
English · Where artifacts live in JENKINS_HOME
▶
How to Find Jenkins Workspace Directory in Linux — CloudBeesTV
English · Workspace directory location

Official docs

Video storyboard (about 80 s)

Shot 1 · 0–20s
Visual: four drawers: workspace (agent), stash, artifacts, fingerprints (controller), each labeled with “when it gets cleared”.
Narration: the workspace stays on the agent, the stash lives only until the build ends, artifacts are kept with the build record, and fingerprints record where files came from.
Shot 2 · 20–45s
Visual: two matrix cells put their reports into the stash drawer, and the Reports stage takes them out and merges them.
Narration: use stash and unstash to pass small files between different workspaces.
Shot 3 · 45–65s
Visual: the build ends and the stash drawer is emptied automatically; on Restart from Stage the drawer is empty, but with preserveStashes it is kept.
Narration: stash is discarded by default when the build ends; only preserveStashes keeps it for restarts.
Shot 4 · 65–80s
Visual: the controller disk gauge needle jumps into the red; the image tar is moved to the registry icon.
Narration: large files do not go into Jenkins; images go to the registry, and Jenkins only records the digest.
or score ≥ 70% on the quiz

Module 6 · Docker builds and containerized agents

35:00 – 42:00 · A “containerized agent” is not another machine: Docker Pipeline starts a container running cat on agent1, then turns each sh into a docker exec
7 mindocker-workflow 653.v2f2c…docker.sock = host root★★★★★
Learning goals
  • Use agent { docker { … } },agent { dockerfile { … } },reuseNode true,args (cache volume), and Scripted docker.image().inside,docker.build,withRun,withRegistry.
  • Based on the plugin source, walk through inside the real command sequence: docker run -t -d -u uid:gid -w ws -v …/--volumes-from … image cat → docker top Validate → each step docker exec → docker stop --time=1 + docker rm -f --volumes.
  • Add an image build (OCI labels) and a redis smoke test for myapp, and reliably clean up containers and networks in post.
  • Evaluate the security cost of “agent mounts the Docker socket” and production alternatives.
Prerequisites:Docker courseimages, containers, networks; the docker agent from Module 3. Importance:★★★★★

What: two ways of “building in Docker”

containerized agent (run steps inside a container)build an image (producing a container image)
Syntaxagent { docker { image 'python:3.13-slim' } },docker.image('…').inside { },agent { dockerfile true }sh 'docker build …',docker.build('myapp:1.1'),image.push()
PurposeDecouple the toolchain from the agent: agent1 does not need Python 3.12/3.13 installedThe deliverable is the image
DependenciesThe agent needs the docker CLI, a working daemon, and a shared filesystem (workspace mount)Same as left (or BuildKit / a remote builder)

How: the real commands behind docker.inside (Docker Pipeline source: WithContainerStep / DockerClient)

  1. Check whether the image exists (docker inspect), and if it does not, docker pull (alwaysPull true when set, always pulls).
  2. Check whether the agent itself runs inside a container: if yes, print agent1 seems to be running inside container <id>, and check whether the workspace lies under one of that container's mount points; if so, use --volumes-from <id>; otherwise, print does not seem to be running inside a container, and use -v workspace:workspace:rw,z bind mount.
  3. docker run -t -d -u 1000:1000 [args] -w <workspace> -v …|--volumes-from … -e ******** … <image> cat Runs as the agent user's uid:gid starts a cat process that waits for input forever, keeping the container alive. Jenkins environment variables are passed in with -e (values masked), but the agent host's own environment variables and PATH are removed.
  4. docker top <id> -eo pid,comm: confirm the container is really running cat. If the image's ENTRYPOINT swallows the command arguments, you will get The container started but didn't run the expected command, so it is recommended to add --entrypoint=''.
  5. Each sh turns into docker exec --env … <id> … (the durable task wrapper still works, and logs are still written under the workspace's @tmp so the controller can still recover after a restart).
  6. End of block: docker stop --time=1 <id>,docker rm -f --volumes <id>.

Five conclusions derived from the mechanism

  • uid mismatch: the process in the container runs as uid 1000, and the image usually has no such user,HOME=/, and writing ~/.cache,pip install --user,npm -g fails with Permission denied → use a venv or a directory inside the project, or environment { HOME = "${WORKSPACE}" }.
  • The image must have cat and sh: distroless and scratch images cannot be used as agents.
  • The workspace must be mountable: when the agent runs inside a container, the workspace must be on a volume (see Lesson 1 on why it is placed /home/jenkins/agent on agent1_work a volume), otherwise the build container sees an empty directory on the host.
  • Every stage-level docker agent is a new container: state inside the container (installed packages) is not kept; only the workspace (mounted) is shared. reuseNode true Let a stage-level docker agent reuse the outer allocated node and workspace.
  • What the container can do = what the daemon can do: steps can docker run -v /:/host. On an agent that mounts the socket, anyone who can edit the Jenkinsfile can get host root.

Why: the value of containerized agents

  • Toolchain versions are written in the Jenkinsfile, so they can be reviewed and rolled back;
  • matrix easily covers multiple versions;
  • the agent machine stays in the minimal form of “only the docker CLI”.

When: which pattern to choose

ScenarioPattern
One toolchain for the whole pipelineTop level agent { docker { image …; label 'linux && docker' } }
Different toolchains in different stagesTop level agent none + stage-level docker agent (this lesson)
Toolchain needs customizationagent { dockerfile { filename 'ci/Dockerfile.ci'; additionalBuildArgs '--pull' } }
Tests need dependent services (redis/postgres)docker.image('redis:7-alpine').withRun { c -> … } or CLI + user-defined network (this lesson's lab)
Jenkins on KubernetesKubernetes plugin Pod agent (Lesson 5); the Docker Pipeline inside is unavailable in Pods without a Docker daemon

Security trade-offs of image builds

OptionIsolationNotes
agent mounts the host /var/run/docker.sock (this lesson's lab)Weakest: equivalent to host rootOnly for personal labs or a dedicated, disposable build machine
Dedicated Docker host / remote BuildKit (docker buildx remote driver)Medium: isolated to a dedicated build machinewith TLS and network isolation
Rootless Docker / rootless BuildKit / BuildahStronger: does not require host rootSome features are restricted (ports, storage driver)
Kubernetes Pod agent + daemonless builderStronger (isolated per Pod)Lesson 5; note that the original Google repository for kaniko is archived, so check its maintenance status when choosing
Common misconceptions① “A docker agent is a new machine”: it is a container on agent1, and the executor still belongs to agent1. ② “inside uses the image's ENTRYPOINT to start the application”: it actually runs cat. ③ “It runs as root in the container”: it runs as the agent's uid. ④ “Docker-in-Docker is safer”: privileged dind is equivalent to host root. ⑤ “After building the image you should archiveArtifacts”: the image is pushed to a registry, and Jenkins only records the digest.

Container relationships in this lab environment

Host Docker daemon (/var/run/docker.sock) jenkins (controller)CPS · queue · stash · artifactsvolume jenkins_home agent1 (linux docker)docker CLI · uid 1000Workspace volume /home/jenkins/agentmounts docker.sock gitealab/myappContainer registry (optional push) remoting python:3.13-slim (build container)Command: cat (keeps it alive)-u 1000:1000 · --volumes-from agent1each sh = docker exec docker run (via the host daemon) Smoke-test network smoke-<BUILD_TAG>redis:7-alpine (alias redis)myapp:1.1-N (alias app, port 5000)curlimages/curl → http://app:5000/healthz
Figure 6-1 All containers are siblings of the host daemon, not nested inside agent1

Interactive: docker.inside, command by command

Step through agent { docker { image 'python:3.13-slim' } } one stage. Turn on the fault switch to see which step the real error comes from.

docker commands issued by agent1
Container and workspace state

Docker Pipeline syntax

SyntaxNotes
agent { docker { image 'python:3.13-slim'; label 'linux && docker'; args '-v pip-cache:/pip-cache'; alwaysPull true } }args appended to docker run; named volume for cache
agent { docker { image '…'; reuseNode true } }stage level: reuse the outer node and workspace (the outer level needs an agent)
agent { docker { image 'registry.example.com/ci/py:3.13'; registryUrl 'https://registry.example.com'; registryCredentialsId 'registry-creds' } }pull the agent image from a private registry
agent { dockerfile { filename 'Dockerfile.ci'; dir 'ci'; additionalBuildArgs '--pull' } }build first, then use
def img = docker.build("myapp:${env.BUILD_NUMBER}", "--label x=y .")The second argument is passed to docker build (a context directory must come last)
docker.withRegistry('http://localhost:3000', 'registry-creds') { img.push(); img.push('latest') }log in, push, and restore at the end of the block
docker.image('redis:7-alpine').withRun('--network-alias redis') { c -> … }start dependency services in the background; automatically removed when the block ends; c.id as the container ID
Manage Jenkins → System → Declarative Pipeline (Docker)global Docker label (the node label the docker agent picks by default) and the default registry
# While the build runs, observe the containers started by inside on the host (command and image columns)
docker ps --format 'table {{.Image}}\t{{.Command}}\t{{.Names}}' | grep -E 'python|redis|myapp'
python:3.13-slim   "cat"                    eloquent_hopper
redis:7-alpine     "docker-entrypoint.s…"   redis-jenkins-myapp-9
myapp:1.1-9        "gunicorn -b 0.0.0.0…"   app-jenkins-myapp-9

How to verify: The COMMAND of the build container is cat; after the build ends, these containers all disappear. Common errors: Calling docker command (the python image has no docker CLI and no socket): a stage that builds images should use a regular label agent. Production use: Push the CI tool image (with pinned versions) to the internal registry and use registryCredentialsId to pull it.

Lab 6: image labels + redis smoke test (about 7 min)

Add OCI labels to the image: in the Build image stage, change docker build one line to:
          docker build \
            --label org.opencontainers.image.revision="$GIT_COMMIT" \
            --label org.opencontainers.image.source="http://gitea:3000/lab/myapp" \
            --label org.opencontainers.image.version="$APP_VERSION" \
            -t "$IMAGE" .
Add a Smoke test stage between Build image and Reports:
    stage('Smoke test') {
      agent { label 'linux && docker' }
      options { skipDefaultCheckout(); timeout(time: 3, unit: 'MINUTES') }
      steps {
        sh '''
          ID=$(printf '%s' "$BUILD_TAG" | tr -c 'A-Za-z0-9_.-' '-')
          docker network create "smoke-$ID"
          docker run -d --name "redis-$ID" --network "smoke-$ID" --network-alias redis redis:7-alpine
          docker run -d --name "app-$ID" --network "smoke-$ID" --network-alias app \
            -e REDIS_HOST=redis -e LOG_LEVEL="$LOG_LEVEL" "$IMAGE"
          ok=0
          for i in $(seq 1 30); do
            if docker run --rm --network "smoke-$ID" curlimages/curl -fsS http://app:5000/healthz; then ok=1; break; fi
            sleep 2
          done
          [ "$ok" = 1 ] || { docker logs "app-$ID" | tail -n 50; exit 1; }
        '''
      }
      post {
        always {
          sh '''
            ID=$(printf '%s' "$BUILD_TAG" | tr -c 'A-Za-z0-9_.-' '-')
            docker rm -f "app-$ID" "redis-$ID" || true
            docker network rm "smoke-$ID" || true
          '''
        }
      }
    }

Key points: no host port is published (so concurrent builds do not clash); container and network names are generated from $BUILD_TAG (e.g. jenkins-myapp-9) to keep them unique, and tr replace illegal characters with -— in Module 7, branch names feature/login will make BUILD_TAG contain %2F, Docker names do not allow %; cleanup goes in post { always }; on failure, print the application log to make troubleshooting easier. LOG_LEVEL Parameters from Module 3 (parameters also appear as environment variables).

Commit and build:
cd ~/jenkinslab/myapp
jcli declarative-linter < Jenkinsfile && git commit -am "Lesson 2: OCI labels + smoke test" && git push
jcli build myapp -s -v | grep -E 'Smoke test|"status"|Finished' | head
N=$(curl -su "admin:$JENKINS_TOKEN" http://127.0.0.1:8080/job/myapp/lastBuild/buildNumber)
docker image inspect "myapp:1.1-$N" --format '{{json .Config.Labels}}'
[Pipeline] { (Smoke test)
{"status":"ok"}
Finished: SUCCESS
{"org.opencontainers.image.revision":"9f2c4e1…","org.opencontainers.image.source":"http://gitea:3000/lab/myapp","org.opencontainers.image.version":"1.1"}

Did the Module 2 post { cleanup } remove the image? This lesson's Jenkinsfile was rewritten in Module 3 and no longer has that cleanup; if you kept it, the image check will fail, which is expected.

(Optional) verify the uid issue with docker.inside: use Replay to add, before the pytest step in Test matrix, sh 'id; echo HOME=$HOME; pip install --user requests || true', and you will see uid=1000 gid=1000,HOME=/ and Permission denied.
(Optional) push to the Gitea container registry: after Module 7 switches to Multibranch, a main branch with PUSH_IMAGE=true runs will execute the Push stage. Prerequisites: Gitea has packages enabled (on by default), and the host Docker can use localhost:3000 to reach Gitea (127.0.0.0/8 allows HTTP registries by default), and Gitea's ROOT_URL must be resolvable by the host (the token auth address comes from ROOT_URL; the one set in Lesson 1 http://localhost:3000/ meets this condition; on Docker Desktop, check in practice). If not, skip it; Lessons 3 and 4 push to ACR/ECR.

Case 1: a PR deleted all the images on the build machine

Problem: An external contributor's PR added sh 'docker system prune -af' to the Jenkinsfile, and the caches of all teams on the shared build machine were cleared. Approach: Fork PR Jenkinsfiles are read only from the target branch (Module 7's trust policy); build machines are isolated by team or trust level; production moves to disposable Pod agents. Limits: As long as the Jenkinsfile can run docker commands, it is equivalent to full control of the daemon.

Case 2: Jenkins on Kubernetes cannot use the docker agent

Problem: After migrating to Kubernetes, all agent { docker { … } } docker stages report docker: not found. Approach: Declare the tool images as multiple containers in a Pod agent (container('python') { sh … }), and hand image builds to a daemonless builder such as BuildKit or Buildah (Lesson 5). Limits: Docker Pipeline depends on an accessible Docker daemon and a shared filesystem.

Case 3: smoke-test port conflict under concurrent builds

Problem: The smoke test uses docker run -p 5000:5000, and when two branches build at the same time, the second one fails port is already allocated. Approach: publish no port; access via a user-defined network per build plus a container alias (this lesson's approach); or -p 127.0.0.1::5000 let Docker assign a random port and look it up. Limits: Networks and containers must be cleaned up in post, or they will accumulate.

Common errors and fixes

ERROR: Could not install packages due to an OSError: [Errno 13] Permission denied: '/.local'

Cause: the container runs as uid 1000,HOME=/ (see the Principles page).

Fix: a venv,--no-cache-dir, or environment { HOME = "${WORKSPACE}" }; do not use args '-u root' as a quick hack (it leaves root-owned files in the workspace, and the next checkout will fail).

python: can't open file …/requirements.txt: [Errno 2] No such file or directory (the workspace is empty inside the container)

Cause: agent1 runs inside a container but its workspace is not on a volume; the log shows but /home/jenkins/agent/workspace/… could not be found among […], and the plugin falls back to -v bind-mounting a same-named path that does not exist on the host.

Fix: the remote root directory must be on a volume: Lesson 1's compose.yaml already uses agent1_work:/home/jenkins/agent ; if you changed the agent's -workDir or deleted this volume, re-check per pre-course step 4.

The container started but didn't run the expected command.

Cause: the image ENTRYPOINT does not run the passed command (the plugin expects cat to be running).

Fix:args '--entrypoint=' (the plugin's suggested --entrypoint='') or switch to an image that follows the official image conventions.

docker: permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock

Cause: the jenkins user on agent1 is not in the socket's group.

Fix: Lesson 1's compose.yaml uses group_add: ["${DOCKER_GID}"] to solve this; after changing machines or upgrading Docker Desktop the GID may change, so regenerate it per Lesson 1, Module 0 .env in the DOCKER_GID and docker compose up -d agent1. Do not chmod 666 docker.sock.

toomanyrequests: You have reached your pull rate limit.

Cause: Docker Hub anonymous pull rate limits (alwaysPull true, and frequent image cleanup makes it worse).

Fix: log in before pulling (registryCredentialsId), use an internal image mirror or pull-through cache, and remove unnecessary alwaysPull.

Command-line tasks
1. Using Scripted's docker global variable: build the image myapp:${BUILD_NUMBER}, then run the smoke test with a redis dependency.
node('linux && docker') {
  checkout scm
  def img = docker.build("myapp:${env.BUILD_NUMBER}")
  def net = "smoke-" + env.BUILD_TAG.replaceAll(/[^A-Za-z0-9_.-]/, '-')
  sh "docker network create ${net}"
  try {
    docker.image('redis:7-alpine').withRun("--network ${net} --network-alias redis") { r ->
      img.withRun("--network ${net} --network-alias app -e REDIS_HOST=redis") { a ->
        sh "for i in \$(seq 1 30); do docker run --rm --network ${net} curlimages/curl -fsS http://app:5000/healthz && exit 0; sleep 2; done; exit 1"
      }
    }
  } finally {
    sh "docker network rm ${net} || true"
  }
}
2. Make the docker agent use the named volume pip-cache as the pip cache.
agent { docker { image 'python:3.13-slim'; label 'linux && docker'; args '-v pip-cache:/pip-cache -e PIP_CACHE_DIR=/pip-cache' } }

Note that a named volume's initial owner is root, so uid 1000 may be unable to write to it; you need to first chown or switch to a directory inside the workspace.

Scenario analysis
The security team requires that build machines must not expose the Docker socket to pipelines, but the team still needs to build images and test on multiple Python versions. Give a design.

Testing: migrate to Kubernetes Pod agents, one container per version (Lesson 5), with no Docker needed. Building: use a daemonless or rootless builder (rootless BuildKit, Buildah), or a controlled remote BuildKit service (exposing only buildkitd, TLS client certificates, pushing only to specified registries). Additional points: fork PRs do not run the push step; sign build artifacts and produce an SBOM; build Pods do not mount host paths. Trade-offs: migration cost and cache performance need to be evaluated.

Verified teaching videos

▶
How to Setup Docker Containers As Build Agents for Jenkins — CloudBeesTV
English · Docker containers as build agents
▶
How to Use Jenkins to Build and Run an Image Using Docker — CloudBeesTV
English · Building and running images in a pipeline
▶
#21 Jenkins Pipelines | Docker Agent (3 use cases) — Extreme Automation - Kamal Girdher
English · Three ways to use the docker agent

Official docs

Video storyboard (about 90 s)

Shot 1 · 0–20s
Visual: agent1 issues a docker run command; a python container appears next to the host daemon, with only one cat process inside.
Narration: a containerized agent is a sibling container that agent1 starts through the host Docker; it only runs cat to stay alive.
Shot 2 · 20–45s
Visual: each sh becomes a docker exec arrow, and the workspace volume is mounted on both agent1 and the build container.
Narration: each step is a docker exec, and the workspace is shared through the same volume.
Shot 3 · 45–70s
Visual: inside the container, the id command shows uid=1000, HOME=/, and pip writing to /.local is rejected.
Narration: the container runs with the agent's uid and its home directory is not writable, so use a virtual environment or a workspace directory.
Shot 4 · 70–90s
Visual: a master key appears on the docker.sock icon, pointing to the host root directory.
Narration: mounting the Docker socket hands host root to the pipeline; in production, replace it with an isolated build approach.
or score ≥ 70% on the quiz

Module 7 · Multibranch, webhooks and PR builds

42:00 – 50:00 · Let Jenkins discover every branch and PR of lab/myapp by itself; a Gitea push triggers a build, and results are written back to the PR page
8 minGitea 286.v0740… · Branch API 2.1303fork PR trust policy★★★★★
Learning goals
  • Explain the parts of a Multibranch Pipeline: branch source (SCM source) → branch, PR and tag discovery (traits) → one child job per branch with a Jenkinsfile → branch indexing and events.
  • Configure the Gitea plugin: Gitea Server (URL, alias URL, whether to manage hooks), branch source (Owner lab, repository myapp, credentials gitea-myapp), and webhook http://jenkins:8080/gitea-webhook/post.
  • Understand PR builds: BRANCH_NAME=PR-n,CHANGE_ID,CHANGE_TARGET,CHANGE_BRANCH,CHANGE_AUTHOR; head and merge checkout strategies; fork PR trust (Nobody / Contributors / Everyone) and the safety mechanism of “loading the Jenkinsfile from the target branch”.
  • Handle the naming and concurrency issues caused by multiple branches (image tags, container names, workspaces).
Prerequisites: when from Module 3; the job types from Lesson 1. Importance:★★★★★

What: Multibranch = one folder + one branch source

A Multibranch Pipeline (plugins Pipeline: Multibranch + Branch API + SCM API) is a computed folder: it periodically, or on events, “indexes” the branch source and creates a child job for each branch, PR or tag that meets the conditions (by default: contains Jenkinsfile) branches, PRs and tags each get one child job (myapp-multibranch/main,myapp-multibranch/PR-1) and, once a branch disappears, deletes the child job per the “orphaned item strategy”. Each child job's Jenkinsfile comes from its own branch (for PRs, see the trust rules below).

Environment variablesBranch buildPR build
BRANCH_NAMEmain,feature/loginPR-3
CHANGE_ID(none)3
CHANGE_TARGET / CHANGE_BRANCH(none)main / feature/login
CHANGE_AUTHOR,CHANGE_TITLE,CHANGE_URL(none)PR author, title, link
JOB_NAME / BUILD_TAGmyapp-multibranch/feature%2Flogin / jenkins-myapp-multibranch-feature%2Flogin-4myapp-multibranch/PR-3

Three configuration points of the Gitea plugin

  1. Gitea Server (Manage Jenkins → System → Gitea Servers): display name, Server URL (the address Jenkins uses to reach Gitea; in this lesson it uses http://gitea:3000), and optional Alias URL (the address Gitea believes it has, i.e. the one it writes into webhook payloads ROOT_URL, e.g. http://localhost:3000— must be set when the two differ, otherwise events will not match the repository), and Manage hooks (once you tick it and provide credentials, Jenkins registers the webhook automatically using Jenkins' root URL).
  2. Branch source (Multibranch job → Branch Sources → Gitea): Server, Credentials (supports the Username with password and Gitea Personal Access Token types; this lesson uses gitea-myapp), Owner lab, Repository myapp, and Behaviours (traits).
  3. Webhook (Gitea repository → Settings → Webhooks → Gitea): Target URL http://jenkins:8080/gitea-webhook/post, POST,application/json. The plugin uses the X-Gitea-Event header to handle push, create/delete, pull_request and other events.

Behaviours (traits)

Trait (UI name)OptionRecommended
Discover branchesOnly branches that are not also filed as PRs / Only branches that are also filed as PRs / All branches / Only branches that are also filed as PRs or master/main branch“Exclude branches that also have an open PR”: avoids building the same commit twice, once as a branch and once as a PR
Discover pull requests from originMerging the pull request with the current target branch revision / The current pull request revision / Bothmerge: tests “what happens after merging” (may need a rebuild each time the target branch changes); head: tests the author's commit itself
Discover pull requests from forksSame as above + Trust: Nobody / Contributors / EveryoneContributors or Nobody; do not choose Everyone
Discover tags / Discover Gitea releases—Turn on when a release pipeline is needed, together with when { buildingTag() }

Why: the fork PR trust mechanism

A Jenkinsfile is code; it runs on the agent and can read the credentials bound to it. If anyone can fork the repository, modify the Jenkinsfile and submit a PR, they can run arbitrary commands on your build machine. So for an untrusted fork PR, Multibranch switches to loading the Jenkinsfile from the target branch (the PR's source code is still checked out, but the pipeline definition is the trusted one), and the log shows Loading trusted files from base branch main at … rather than …. Note: this only protects the “pipeline definition”; the PR's Makefile, and test code is still executed. Untrusted PRs should be built on isolated agents with no sensitive credentials.

How: events vs. scans

  • Event: webhook → /gitea-webhook/post → the plugin generates an SCM event → the Branch API finds the matching Multibranch item → creates a child job if needed → schedules the build. Within seconds.
  • Scan (Scan Multibranch Pipeline Now / periodic scan): lists all branches, PRs and tags via the Gitea API, compares revisions, and fills in missed events. When webhooks are present, set the period long (e.g. 1 day) as a fallback.
  • Security note: based on the 2026-11 plugin source, the Gitea plugin's webhook endpoint has no signature (secret) verification logic; the revision in an event still has to exist in Gitea to be checked out, but forged requests can trigger scans or builds. Restrict at the network layer who can reach /gitea-webhook/post (in this lesson it is reachable only inside the Compose network).

When

  • If the team uses a PR workflow → Multibranch (single repository) or Organization Folder (all repositories under an organization or user; the Gitea plugin supports it too).
  • Only one fixed branch with complex manual parameters → a regular Pipeline job also works.

Comparison with similar technologies

Jenkins MultibranchGitHub ActionsAzure Pipelines
PR triggerWebhook / scanon: pull_requestPR triggers / build validation in branch policies
fork PR protectiontrust policy + target-branch Jenkinsfilepull_request no secrets, approval required to runfork builds get no secrets by default
Status write-backthe plugin writes back commit statusnative checksnative status
Common misconceptions① “Once the webhook is set up, scanning is unnecessary”: the first scan must happen to create child jobs, and periodic scanning is the fallback when events are lost. ② “A PR's Jenkinsfile always comes from the PR branch”: untrusted fork PRs use the target branch's. ③ “PR-3 builds the author's commit”: under the merge strategy, what is built is the temporary commit that results from merging the PR into the target branch. ④ “Deleting a branch deletes its build records immediately”: this is decided by the orphaned item strategy.

Full path from webhook to commit status

Developergit push / open PR gitea (:3000) lab/myapp WebhookX-Gitea-Event: push commit status…/pipeline/head ✓ POST jenkins (:8080) /gitea-webhook/post → SCM event Branch API: match myapp-multibranchread head/PR via Gitea API (credentials gitea-myapp) child jobs: main · PR-3 · feature/loginfork and untrusted → target branch Jenkinsfile GiteaNotifier: write back status agent1separate workspace per branchrun Jenkinsfile
Figure 7-1 Events are only “hints”; Jenkins still reads the real branch and PR information through the Gitea API

head and merge PR revisions

main latest on target branch feature/login PR head merge revision (temporary merge commit)
Figure 7-2 The head strategy builds the yellow commit; the merge strategy builds the blue temporary merge result

Interactive: the journey of one event

Choose an event type and step through what happens between Gitea, Jenkins and agent1.

Multibranch-related commands and endpoints

Command / endpointPurpose
jcli build myapp-multibranch“Build” on a Multibranch folder = trigger one branch indexing (scan)
curl -su admin:$JENKINS_TOKEN http://127.0.0.1:8080/job/myapp-multibranch/indexing/consoleTextView the log of the latest scan
jcli build 'myapp-multibranch/main' -p PUSH_IMAGE=true -sBuild a branch child job (with parameters)
jcli list-jobs myapp-multibranchList the discovered branches / PRs
http://127.0.0.1:8080/job/myapp-multibranch/job/feature%252Flogin/containing / branches are URL-encoded twice in the URL (%252F)
POST http://jenkins:8080/gitea-webhook/postGitea plugin webhook endpoint (address inside the Compose network)
curl -s -u lab:$GITEA_TOKEN http://127.0.0.1:3000/api/v1/repos/lab/myapp/hooksList repository webhooks with the Gitea API
curl -su "admin:$JENKINS_TOKEN" http://127.0.0.1:8080/job/myapp-multibranch/indexing/consoleText | tail -n 12
Checking branch main
      ‘Jenkinsfile’ found
    Met criteria
Scheduled build for branch: main
Checking branch feature/login
      ‘Jenkinsfile’ found
    Met criteria
Scheduled build for branch: feature/login
  2 branches were processed
Finished: SUCCESS

How to verify: On the Gitea webhook page, “Recent Deliveries” shows a 200 response; the Jenkins system log shows event-handling records. Common errors: Webhook URL is set to http://localhost:8080/…— inside the gitea container, localhost refers to itself. Production use: An Organization Folder onboards a whole organization at once.

Lab 7: myapp Multibranch + Gitea webhook + PR (about 9 min)

Check the Gitea webhook host restriction and ROOT_URL: Gitea by default only allows webhooks to external addresses (ALLOWED_HOST_LIST default external), while the Compose-internal jenkins is a private address. Lesson 1's compose.yaml already sets GITEA__webhook__ALLOWED_HOST_LIST: "private", here it is only confirmed:
cd ~/jenkinslab
docker compose exec gitea env | grep -E 'ALLOWED_HOST_LIST|ROOT_URL'
GITEA__server__ROOT_URL=http://localhost:3000/
GITEA__webhook__ALLOWED_HOST_LIST=private

private Allowing all private addresses is only suitable for lab environments; in production, specify concrete hostnames or CIDRs. ROOT_URL is http://localhost:3000/, which differs from the http://gitea:3000 used by Jenkins, so fill it into Alias URL in the next step.

Configure the Gitea Server: Manage Jenkins → System → Gitea Servers → Add: Display name gitea-local, Server URL http://gitea:3000,, leave unchecked Manage hooks (this lab registers hooks by hand, to avoid Jenkins using http://localhost:8080/ this root URL to register an address that gitea cannot reach), and in advanced options fill Alias URL with the ROOT_URL from the previous step (e.g. http://localhost:3000). Save.
Adapt for multibranch naming: several branches may share the same build number, so myapp:1.1-6 would overwrite each other. In the Jenkinsfile's top-level environment block, delete the IMAGE = … line, and in stages { add the following as the first entry under
    stage('Prepare') {
      steps {
        script {
          def safe = env.BUILD_TAG.replaceAll(/[^A-Za-z0-9_.-]/, '-').toLowerCase()
          env.IMAGE = "myapp:${env.APP_VERSION}-${safe}"
        }
        echo "BRANCH_NAME=${env.BRANCH_NAME} CHANGE_ID=${env.CHANGE_ID} IMAGE=${env.IMAGE}"
      }
    }

This stage has no agent (the top-level is agent none), so it runs only controller-side Groovy and echo and takes no executor. Note: environment variables defined in an environment directive cannot be script { env.X = … } overwritten, so you must first remove IMAGE from environment.

Create a Multibranch job: New Item → name myapp-multibranch → Multibranch Pipeline:
  • Branch Sources → Add source → Gitea: Server gitea-local, Credentials gitea-myapp, Owner lab, Repository myapp.
  • Behaviours: Discover branches (Only branches that are not also filed as PRs); Discover pull requests from origin (Merging the pull request with the current target branch revision); Discover pull requests from forks (same as above, Trust: Contributors).
  • Build Configuration: by Jenkinsfile, Script Path Jenkinsfile.
  • Scan Multibranch Pipeline Triggers: Periodically if not otherwise run, interval 1 day.
  • Orphaned Item Strategy: Discard old items, Days to keep 7.
After saving, a scan runs automatically. Then commit the Jenkinsfile change from the previous step:
cd ~/jenkinslab/myapp
jcli declarative-linter < Jenkinsfile && git commit -am "Lesson 2: branch-safe image tags" && git push
jcli list-jobs myapp-multibranch
main
Register the webhook (Gitea UI: lab/myapp → Settings → Webhooks → Add Webhook → Gitea; or use the API):
# GITEA_TOKEN comes from pre-course step 2 (~/jenkinslab/.secrets/gitea-token, scope write:repository, which is enough to manage webhooks)
curl -s -u "lab:$GITEA_TOKEN" -H 'Content-Type: application/json' \
  -X POST http://127.0.0.1:3000/api/v1/repos/lab/myapp/hooks -d '{
    "type": "gitea",
    "active": true,
    "events": ["push", "create", "delete", "pull_request"],
    "config": { "url": "http://jenkins:8080/gitea-webhook/post", "content_type": "json" }
  }' | grep -o '"url":"[^"]*"' | head -1
"url":"http://jenkins:8080/gitea-webhook/post"

On the webhook page, click Test Delivery, Recent Deliveries should show 200.

Trigger builds with a branch and a PR:
cd ~/jenkinslab/myapp
git switch -c feature/login
echo "# login feature placeholder" >> README.md
git commit -am "feature: login placeholder" && git push -u origin feature/login
sleep 10; jcli list-jobs myapp-multibranch
# Create the PR on Gitea (the UI also works)
curl -s -u "lab:$GITEA_TOKEN" -H 'Content-Type: application/json' -X POST \
  http://127.0.0.1:3000/api/v1/repos/lab/myapp/pulls \
  -d '{"title":"feature: login","head":"feature/login","base":"main"}' | grep -o '"number":[0-9]*'
sleep 15; jcli list-jobs myapp-multibranch
feature%2Flogin
main
"number":1
PR-1
main

After opening the PR, under the “Only branches that are not also filed as PRs” strategy,feature/login the branch job is treated as orphaned (kept for 7 days under the orphaned item strategy, then deleted), and in its place there is PR-1. On the Gitea PR page you can see the commit status written back by Jenkins (the context name looks like myapp-multibranch/pipeline/…, depending on the actual plugin; you need gitea-myapp write permission on the repository).

Verify when and PR variables:
curl -su "admin:$JENKINS_TOKEN" http://127.0.0.1:8080/job/myapp-multibranch/job/PR-1/lastBuild/consoleText \
  | grep -E 'BRANCH_NAME=|Stage "Push" skipped|Finished'
jcli build myapp-multibranch/main -p PUSH_IMAGE=true -s -v | grep -E 'Stage "Push"|docker push|Finished'
BRANCH_NAME=PR-1 CHANGE_ID=1 IMAGE=myapp:1.1-jenkins-myapp-multibranch-pr-1-1
Stage "Push" skipped due to when conditional
Finished: SUCCESS
The push refers to repository [localhost:3000/lab/myapp]
Finished: SUCCESS

On PR-1, the Push stage is skipped (branch 'main' is false); on main, with parameters, Push runs (pushing needs the prerequisites from Module 6 Lab step 5, otherwise the Push stage fails; it is enough to observe that the Push stage runs).

Disable the single-branch job: Multibranch has replaced Lesson 1's myapp, so disable it to avoid building the same commit twice (keep the build records for comparison): jcli disable-job myapp.

Case 1: all webhooks return 200, but Jenkins does nothing

Problem: Gitea's ROOT_URL is https://git.example.com/, while Jenkins' Server URL uses the internal address http://gitea.internal:3000, so the repository address in the event matches none of the configured servers, and the plugin silently ignores it. Approach: Fill in Alias URL in the Gitea Server. Limits: Only one Gitea Server entry can be configured for the same Gitea, otherwise matching gets confused.

Case 2: an external contributor's PR read deployment credentials

Problem: Trust was set to Everyone, and the attacker's PR modified the Jenkinsfile to print registry-creds (base64 bypasses masking). Approach: Change Trust to Contributors; add when { not { changeRequest() } } to the push and deploy stages; keep deployment credentials in a folder credential domain that only the main branch can access, or use environment approval (Lesson 6). Limits: Even when the Jenkinsfile is trusted, test code in the PR still runs.

Case 3: every merge to main triggers 80 PR rebuilds

Problem: The PR discovery strategy is merge. After the target branch changes, the scan finds that the merge revision of every PR has changed, so all of them are rebuilt and the agent pool is saturated. Approach: Switch to the head strategy and require the branch to be in sync with the target before merging; or keep merge but suppress automatic triggering in the Branch API properties and build only when the PR itself is updated. Limits: The head strategy cannot discover conflicts and regressions that only appear after merging.

Common errors and fixes

Gitea webhook delivery failed: webhook can only call allowed HTTP servers (check your webhook.ALLOWED_HOST_LIST setting)

Cause: the target is a private address, which Gitea blocks by default.

Fix: confirm GITEA__webhook__ALLOWED_HOST_LIST (Lesson 1 already set it to private; the exact wording of the error depends on the Gitea version).

Webhook delivery returns 200, but no build is triggered

Cause: Alias URL not configured, so events do not match; Multibranch has never scanned; the branch has no Jenkinsfile; the event type is not ticked.

curl -su "admin:$JENKINS_TOKEN" http://127.0.0.1:8080/job/myapp-multibranch/indexing/consoleText | tail

Fix: add the Alias URL, trigger a manual scan once, and check the webhook's event list.

Webhook delivery error: dial tcp: lookup localhost … connection refused

Cause: Target URL is written as http://localhost:8080/…, and inside the gitea container localhost refers to itself.

Fix: use the Compose service name http://jenkins:8080/gitea-webhook/post.

Commit status not shown in Gitea / build log HTTP 403 Forbidden (status)

Cause: Plugin docs note that since Gitea 1.16.9, the user that writes statuses back needs repository code write permission.

Fix: Grant gitea-myapp write permission on the corresponding user repository, or use a token with the appropriate permissions.

Loading trusted files from base branch main at … rather than … (my Jenkinsfile changes did not take effect)

Cause: the PR comes from a fork and its author is not trusted, so the Jenkinsfile is taken from the target branch.

Fix: This is by design for security; have a maintainer commit the Jenkinsfile change on a trusted branch, or adjust the trust policy (with caution).

Command-line tasks
1. Write a stage condition that runs only for PR builds whose target branch is main, and print the PR number and source branch.
stage('PR checks') {
  when { beforeAgent true; changeRequest target: 'main' }
  steps { echo "PR #${env.CHANGE_ID} from ${env.CHANGE_BRANCH} by ${env.CHANGE_AUTHOR}" }
}
2. Use curl to trigger a Multibranch scan and view the scan log.
curl -su "admin:$JENKINS_TOKEN" -X POST http://127.0.0.1:8080/job/myapp-multibranch/build
sleep 5
curl -su "admin:$JENKINS_TOKEN" http://127.0.0.1:8080/job/myapp-multibranch/indexing/consoleText | tail
Scenario analysis
An open-source project uses Jenkins + Gitea and wants fork PRs to run tests, but they must never touch image registry credentials or the internal network. Give a design.

① Set Fork PR Trust to Contributors (PRs from non-contributors use the target branch's Jenkinsfile). ② The test stage runs on a dedicated isolated agent label (for example untrusted), which has no network route to internal systems, no Docker socket, and is disposable (Pod or VM discarded after use). ③ Push and deploy stages: when { allOf { branch 'main'; not { changeRequest() } } }, with credentials in a scope that only main can use. ④ After maintainer review, a higher-trust build can be triggered manually. ⑤ Limit /gitea-webhook/post to accept network traffic only from Gitea.

Verified teaching videos

▶
How to Create a Gitea Organization in Jenkins — CloudBeesTV
English · Gitea plugin and organization folders
▶
Jenkins Multibranch Pipeline With Git Tutorial — CloudBeesTV
English · Multibranch basics
▶
Create Multibranch Pipeline with Git - Jenkins Pipeline Tutorial for Beginners 2/4 — TechWorld with Nana
English · Multibranch and branch conditions (recorded earlier)
▶
How to Create a GitHub Branch Source Multibranch Pipeline in Jenkins — CloudBeesTV
English · GitHub branch source (concepts are the same as Gitea)

Official docs

Video storyboard (about 90 s)

Shot 1 · 0–20s
Visual: the Multibranch folder automatically grows three child jobs: main, feature/login, PR-1.
Narration: Multibranch scans the branch source and creates a child job for each branch and PR that contains a Jenkinsfile.
Shot 2 · 20–45s
Visual: after git push, Gitea sends a POST to gitea-webhook/post, and Jenkins queries the Gitea API and then schedules the build.
Narration: the webhook is only a hint; Jenkins uses its credentials to go back to Gitea and confirm the real branches and commits.
Shot 3 · 45–70s
Visual: the Jenkinsfile of the fork PR is greyed out, and the target branch's Jenkinsfile replaces it.
Narration: an untrusted fork PR uses the target branch's Jenkinsfile, so nobody can change the pipeline to steal credentials.
Shot 4 · 70–90s
Visual: a green check status appears on the Gitea PR page.
Narration: the build result is written back to the PR as a gate before merging.
or score ≥ 70% on the quiz

Module 8 · CI readiness review and common failures

50:00 – 60:00 · Use a checklist to review myapp's Jenkinsfile, then use fault injection to practice the “read logs → locate the layer → fix” troubleshooting path
10 minReview checklist · troubleshooting tree★★★★★
Learning goals
  • Review a Jenkinsfile along five dimensions (correctness, speed, security, maintainability, observability) and give actionable change suggestions.
  • Assign errors to the right layer: Groovy/CPS (controller), Declarative validation, scheduling (labels and executors), agent/container, SCM/webhook, and the step command itself.
  • Use Replay, Restart from Stage, the Pipeline Graph View step logs,indexing/consoleText and Gitea Recent Deliveries to locate problems.
Prerequisites: Modules 1–7. Importance:★★★★★

What: CI readiness review checklist (myapp version)

DimensionCheck itemCovered in this lesson
CorrectnessDeclarative,declarative-linter passesM2
each stage explicitly declares its agent (top-level agent none or an explicit label), and never builds on the Built-In NodeM3
test reports come from this build (junit empty or stale reports are not allowed; a test failure fails the buildM5
artifact names are unique across branches (image tags, container names, network names)M6, M7
Speedindependent checks run in parallel; the number of branches matches the number of executorsM4
skipped stages use beforeAgent trueM3
build and test pipelines can consider PERFORMANCE_OPTIMIZED; disableConcurrentBuilds(abortPrevious: true)M1, M3
Securitycredentials are passed only through credentials()/withCredentials binding, single-quoted references, no Groovy interpolation warningsM3
push and deploy stages run only on main (not on PRs)M3, M7
fork PR trust policy is not EveryoneM7
the Docker socket risk and the replacement plan are documentedM6
Maintainabilitylittle Groovy logic (no large script, no JsonSlurper/Jenkins.instance)M1, M2
toolchain versions are written in image tags (python:3.13-slim), no “latest”M6
parameter defaults are safe (PUSH_IMAGE=false)M3
Observability and resourcestimeout,timestamps(),buildDiscarderM2, M5
diagnostics printed on failure (application log, test report), artifacts downloadableM5, M6
in post, clean up containers, networks, temporary images and the workspaceM5, M6

Why: classify first, then look at details

LayerTypical signalWhere to look first
Declarative validationWorkflowScript: N: …, 0 steps executedlinter, Jenkinsfile line number
Groovy / CPS / sandboxNotSerializableException,RejectedAccessException,MissingPropertyExceptionin the stack trace WorkflowScript.run line numbers; In-process Script Approval
Scheduling“Waiting for next available executor”, “There are no nodes with the label”Nodes page, labels, queue (Lesson 7)
agent / containerdocker: permission denied docker.sock, uid/HOME, empty workspaceagent logs,docker inspect
SCM / Webhookno build, builds an old commit, PR does not appearindexing logs, Gitea Recent Deliveries
the command itselfnon-zero exit code (script returned exit code 1)step logs, test reports

How: debugging tools

  • Pipeline Graph View: view steps and logs by stage or branch; locate the failed step directly.
  • Replay: without committing, add sh 'env | sort',sh 'id; ls -la' and other diagnostic statements.
  • Restart from Stage: re-run only the failed top-level stage (together with preserveStashes).
  • Full console: …/lastBuild/consoleText easy to grep.
  • System log: Manage Jenkins → System Log; controller container logs docker compose logs jenkins.

When

Run a review whenever a new pipeline is added, a new agent type is introduced, fork PRs are opened up, or build times grow significantly. Put the checklist in the repository's PULL_REQUEST_TEMPLATE , and changes to the Jenkinsfile require maintainer approval.

Common misconceptions① “Green means ready”: green may come from skipped tests and stale reports. ② “Adding retry and catchError makes it stable”: that is masking the problem. ③ “Fixing it in Replay is enough”: the fix must go into the repository. ④ “If the build is slow, add executors”: first check whether the Groovy is too heavy, the stages are too fragmented, or the cache is invalid.

Error layer diagnosis

Trigger: webhook / scan / manual / scheduled → indexing logs · Recent Deliveries Parsing and validation (controller): WorkflowScript: N … · linter CPS / sandbox (controller): NotSerializableException · RejectedAccessException · CPS mismatch Scheduling: labels · executors · queue (Lesson 7) agent / container: docker.sock · uid/HOME · workspace volume · image pull The command itself: script returned exit code N · test reports
Figure 8-1 Troubleshoot from top to bottom: when an upper layer fails, the lower layers never run

Final pipeline for this lesson

Prepare Static checksPython syntaxDockerfile lint Test matrixPY 3.12PY 3.13 Build image Smoke test Reports Pushmain + parameters
Figure 8-2 Review target: the Jenkinsfile built step by step in this lesson (full content is on the Lab page)

Interactive: CI readiness scorecard

Tick off the items your Jenkinsfile satisfies (saved in this browser). A score ≥ 85 lets you proceed to Lesson 3's cloud deployment.

Troubleshooting command list

CommandPurpose
jcli declarative-linter < JenkinsfileStructure validation
curl -su admin:$JENKINS_TOKEN …/job/myapp-multibranch/job/main/lastBuild/consoleText | grep -nE 'ERROR|Exception|exit code'quickly locate the error line
jcli replay-pipeline myapp-multibranch/main -n 12 < debug.groovyCLI Replay
jcli get-node agent1 / jcli list-jobs myapp-multibranchlabels and branch jobs
docker compose logs --since 10m jenkins agent1 gitearecent logs of the three services
docker compose exec agent1 docker ps -a --filter status=exitedleftover build containers
curl -su admin:$JENKINS_TOKEN 'http://127.0.0.1:8080/queue/api/json?tree=items[why,task[name]]'why builds in the queue are waiting
curl -su "admin:$JENKINS_TOKEN" 'http://127.0.0.1:8080/queue/api/json?tree=items[why,task[name]]'
{"_class":"hudson.model.Queue","items":[{"_class":"hudson.model.Queue$BuildableItem","task":{"_class":"org.jenkinsci.plugins.workflow.support.steps.ExecutorStepExecution$PlaceholderTask"},"why":"Waiting for next available executor on ‘agent1’"}]}

How to verify:why the fields directly state the reason for queuing. Common errors: only looking at the last line “Finished: FAILURE” and not at the first error. Production use: Turn these queries into an on-call runbook (Lesson 7).

Lab 8: review the final Jenkinsfile and do fault injection (about 10 min)

Check the final Jenkinsfile (the accumulated result of Modules 2–7; you can use it to overwrite the file in the repository directly):
pipeline {
  agent none
  options {
    buildDiscarder(logRotator(numToKeepStr: '20', artifactNumToKeepStr: '5'))
    timeout(time: 20, unit: 'MINUTES')
    timestamps()
    disableConcurrentBuilds(abortPrevious: true)
    skipStagesAfterUnstable()
    preserveStashes(buildCount: 3)
  }
  parameters {
    booleanParam(name: 'PUSH_IMAGE', defaultValue: false, description: 'Push the image after the build (only effective on the main branch)')
    choice(name: 'LOG_LEVEL', choices: ['INFO', 'DEBUG'], description: 'Log level for the smoke test')
  }
  environment {
    APP_VERSION = '1.1'
    REGISTRY = 'localhost:3000/lab'
  }
  stages {
    stage('Prepare') {
      steps {
        script {
          def safe = env.BUILD_TAG.replaceAll(/[^A-Za-z0-9_.-]/, '-').toLowerCase()
          env.IMAGE = "myapp:${env.APP_VERSION}-${safe}"
        }
        echo "BRANCH_NAME=${env.BRANCH_NAME} CHANGE_ID=${env.CHANGE_ID} IMAGE=${env.IMAGE}"
      }
    }
    stage('Static checks') {
      failFast true
      parallel {
        stage('Python syntax') {
          agent { docker { image 'python:3.13-slim'; label 'linux && docker' } }
          steps { sh 'python -m compileall -q -x "/\\.venv/" .' }
        }
        stage('Dockerfile lint') {
          agent { label 'linux && docker' }
          steps {
            catchError(buildResult: 'SUCCESS', stageResult: 'UNSTABLE') {
              sh 'docker run --rm -i hadolint/hadolint < Dockerfile'
            }
          }
        }
      }
    }
    stage('Test matrix') {
      matrix {
        axes {
          axis { name 'PY'; values '3.12', '3.13' }
        }
        agent { docker { image "python:${PY}-slim"; label 'linux && docker' } }
        stages {
          stage('pytest') {
            options { timeout(time: 5, unit: 'MINUTES', activity: true) }
            steps {
              sh '''
                python -m venv .venv
                . .venv/bin/activate
                pip install --no-cache-dir -q -r requirements-dev.txt
                rm -rf reports && mkdir -p reports
                pytest -q --junitxml="reports/junit-py$PY.xml"
              '''
            }
            post {
              always {
                junit testResults: "reports/junit-py${PY}.xml", allowEmptyResults: false
                stash name: "reports-py${PY}", includes: 'reports/*.xml', allowEmpty: true
              }
            }
          }
        }
      }
    }
    stage('Build image') {
      agent { label 'linux && docker' }
      steps {
        sh '''
          docker build \
            --label org.opencontainers.image.revision="$GIT_COMMIT" \
            --label org.opencontainers.image.source="http://gitea:3000/lab/myapp" \
            --label org.opencontainers.image.version="$APP_VERSION" \
            -t "$IMAGE" .
          mkdir -p meta
          docker image inspect --format '{{.Id}}' "$IMAGE" > meta/image-id.txt
        '''
        stash name: 'meta', includes: 'meta/*'
      }
    }
    stage('Smoke test') {
      agent { label 'linux && docker' }
      options { skipDefaultCheckout(); timeout(time: 3, unit: 'MINUTES') }
      steps {
        sh '''
          ID=$(printf '%s' "$BUILD_TAG" | tr -c 'A-Za-z0-9_.-' '-')
          docker network create "smoke-$ID"
          docker run -d --name "redis-$ID" --network "smoke-$ID" --network-alias redis redis:7-alpine
          docker run -d --name "app-$ID" --network "smoke-$ID" --network-alias app \
            -e REDIS_HOST=redis -e LOG_LEVEL="$LOG_LEVEL" "$IMAGE"
          ok=0
          for i in $(seq 1 30); do
            if docker run --rm --network "smoke-$ID" curlimages/curl -fsS http://app:5000/healthz; then ok=1; break; fi
            sleep 2
          done
          [ "$ok" = 1 ] || { docker logs "app-$ID" | tail -n 50; exit 1; }
        '''
      }
      post {
        always {
          sh '''
            ID=$(printf '%s' "$BUILD_TAG" | tr -c 'A-Za-z0-9_.-' '-')
            docker rm -f "app-$ID" "redis-$ID" || true
            docker network rm "smoke-$ID" || true
          '''
        }
      }
    }
    stage('Reports') {
      agent { label 'linux && docker' }
      options { skipDefaultCheckout() }
      steps {
        unstash 'reports-py3.12'
        unstash 'reports-py3.13'
        unstash 'meta'
        sh '''
          {
            echo "image: $IMAGE"
            echo "id:    $(cat meta/image-id.txt)"
            for f in reports/*.xml; do
              printf '%s tests=%s failures=%s\n' "$f" \
                "$(grep -o 'tests="[0-9]*"' "$f" | head -1 | tr -dc 0-9)" \
                "$(grep -o 'failures="[0-9]*"' "$f" | head -1 | tr -dc 0-9)"
            done
          } > reports/summary.txt
          cat reports/summary.txt
        '''
        archiveArtifacts artifacts: 'reports/**, meta/image-id.txt', fingerprint: true
      }
      post { cleanup { cleanWs() } }
    }
    stage('Push') {
      agent { label 'linux && docker' }
      when {
        beforeAgent true
        allOf { branch 'main'; not { changeRequest() }; expression { params.PUSH_IMAGE } }
      }
      environment { REG = credentials('registry-creds') }
      steps {
        sh '''
          echo "$REG_PSW" | docker login localhost:3000 -u "$REG_USR" --password-stdin
          docker tag "$IMAGE" "$REGISTRY/$IMAGE"
          docker push "$REGISTRY/$IMAGE"
          docker logout localhost:3000
        '''
      }
    }
  }
  post {
    always { echo "Result: ${currentBuild.currentResult}; IMAGE=${env.IMAGE}; PUSH_IMAGE=${params.PUSH_IMAGE}" }
  }
}

Two wrap-up changes compared with earlier modules: Dockerfile lint is changed to catchError(buildResult: 'SUCCESS', stageResult: 'UNSTABLE') (warnings are visible but do not block the image build); before pytest rm -rf reports to prevent stale reports; Push adds not { changeRequest() } as a second safety net.

Commit and score: commit to main, wait for the webhook to trigger a successful build, then score yourself on the scorecard on the “Animation” tab.
cd ~/jenkinslab/myapp && git switch main && git pull --ff-only
jcli declarative-linter < Jenkinsfile && git commit -am "Lesson 2: final version after review" && git push
sleep 60; curl -su "admin:$JENKINS_TOKEN" http://127.0.0.1:8080/job/myapp-multibranch/job/main/lastBuild/api/json?tree=result,number
{"_class":"org.jenkinsci.plugins.workflow.job.WorkflowRun","number":4,"result":"SUCCESS"}
Fault injection ①: wrong label. On the feature branch, change the label of one stage to 'linux && dockr' and push; observe the build stuck in the queue,queue/api/json the why reads There are no nodes with the label ‘linux&&dockr’ (wording depends on the version). Abort the build and fix it.
Fault injection ②: mismatched stash name. Use Replay to change unstash 'reports-py3.12' in Reports to 'reports-3.12', and see No such saved stash; after fixing it, use Restart from Stage → Reports to verify preserveStashes.
Fault injection ③: wrong webhook address. In Gitea, change the webhook URL to http://localhost:8080/gitea-webhook/post, push a commit: Recent Deliveries shows a connection failure and Jenkins has no build; change it back to http://jenkins:8080/… and click Test Delivery.
Fault injection ④: test failure. Make a test assertion fail on the feature branch and open a PR: the PR build is FAILURE, the Test Result shows the failing case, Smoke test and Push do not run, and the Gitea PR page status is failed. Then close the PR and delete the branch.

Case 1: the review found a pipeline that had been “green for three months” without running any tests

Problem:sh 'pytest || true' + junit allowEmptyResults: true, after the test directory was renamed, pytest collected 0 tests and exited with code 5, which was || true swallowed. Approach: remove || true,allowEmptyResults: false, and in the Reports stage check tests>0. Limits: coverage and other metrics are still needed to guard against “too few tests”.

Case 2: build time rose from 6 min to 25 min

Problem: The review found 1) every skipped deploy stage still allocates an agent first; 2) every small check is its own docker agent stage (9 image starts + checkouts); 3) alwaysPull true triggers Docker Hub rate limiting and retries. Approach: beforeAgent, merging small checks, an internal image cache. Limits: merging stages reduces visualization granularity; compensate with log sections.

Case 3: after a controller restart, all PR builds “hung”

Problem: agents are auto-scaled temporary VMs; during the controller restart they were scaled in, and the builds after recovery wait for agents to reconnect. Approach: PR pipelines set disableResume() (re-triggering after a failure is enough); deployment pipelines keep resume capability; pause automatic scale-in before the upgrade window. Limits: builds with disableResume are marked as failed, so a notification mechanism is needed.

Interactive troubleshooting tree

Choose step by step based on the symptom to get the diagnosis and the fix commands.

Quick reference for frequent errors

script returned exit code 1

This is not a Jenkins error, but a failed command. Scroll up to the first error output of that step; use Replay to add set -x.

Required context class hudson.FilePath is missing / Perhaps you forgot to surround the code with a step that provides this, such as: node

Cause: in a stage without an agent (such as Prepare), a workspace-dependent step was called (sh,readFile).

Fix: add an agent to that stage, or keep only pure Groovy and echo in the script.

hudson.AbortException: … Cancelled / Aborted by anonymous

Cause:disableConcurrentBuilds(abortPrevious: true) a new build on the same branch aborted the old build; this is expected behavior.

Command-line tasks
1. Query the reasons why each waiting item in the queue is waiting.
curl -su "admin:$JENKINS_TOKEN" 'http://127.0.0.1:8080/queue/api/json?tree=items[why,task[name]]'
2. Extract all lines containing ERROR or Exception (with line numbers) from the console of the latest build on main.
curl -su "admin:$JENKINS_TOKEN" http://127.0.0.1:8080/job/myapp-multibranch/job/main/lastBuild/consoleText \
  | grep -nE 'ERROR|Exception'
Scenario analysis
You take over a Jenkinsfile with a top-level agent any, 600 lines of Groovy,sh "docker login -p ${PASS}", no timeout, and a deploy stage that runs on all branches. Give the top five remediation items in priority order.

1) Security: change credentials to single quotes + --password-stdin; add to the deploy stage when { branch 'main'; not { changeRequest() }; beforeAgent true }. 2) Resources: add timeout,buildDiscarder. 3) Scheduling: agent none + explicit label, forbid building on the Built-In Node. 4) Maintainability: move the Groovy logic into agent scripts or a shared library, and keep the orchestration. 5) Observability: junit, artifacts, failure diagnostics, Pipeline Graph View. Also: add the linter to PR checks, and review the fork PR trust policy.

Verified teaching videos

▶
How To Restart a Jenkins Pipeline From a Stage — CloudBeesTV
English · Restart from a stage after a failure
▶
What Does disableRestartFromStage Mean in Jenkins — CloudBeesTV
English · When to disable Restart from Stage
▶
Jenkinsfile - Jenkins Pipeline Tutorial for Beginners 3/4 — TechWorld with Nana
English · Recap of common Jenkinsfile patterns (recorded earlier)

“CI readiness review” topic: No verified dedicated video found, so use this module's checklist as the reference.

Official docs

Video storyboard (about 90 s)

Shot 1 · 0–25s
Visual: the five dimensions of the review checklist light up one by one, and the corresponding Jenkinsfile lines are highlighted beside them.
Narration: the review checks the Jenkinsfile along five dimensions: correctness, speed, security, maintainability, and observability.
Shot 2 · 25–50s
Visual: a layered error diagram, with a red error falling from the top and stopping at the “scheduling” layer.
Narration: troubleshoot layer by layer; when an upper layer fails, the lower layers never run.
Shot 3 · 50–75s
Visual: in the Replay editor, insert env and id commands; Restart from Stage continues from Reports.
Narration: Replay is for inserting diagnostics; Restart from Stage is for re-running only the part that failed.
Shot 4 · 75–90s
Visual: the scorecard reaches 85 points, and the gate opens to “Lesson 3 Azure”.
Narration: once the pipeline passes the review, you can move on to cloud deployment.
or score ≥ 70% on the quiz

Command cheat sheet

Declarative syntax, steps, jenkins-cli commands and endpoints used in this lesson
Declarative skeleton
pipeline {
  agent none
  options { timeout(time: 20, unit: 'MINUTES'); timestamps()
            buildDiscarder(logRotator(numToKeepStr: '20')) }
  parameters { booleanParam(name: 'PUSH_IMAGE', defaultValue: false) }
  environment { APP_VERSION = '1.1' }
  stages {
    stage('x') {
      agent { label 'linux && docker' }
      when { beforeAgent true; branch 'main' }
      steps { sh 'make' }
      post { always { junit 'reports/*.xml' } }
    }
  }
  post { failure { echo 'failed' } cleanup { echo 'bye' } }
}
Execution model (M1)
options { durabilityHint('PERFORMANCE_OPTIMIZED') }Performance first
options { disableResume() }Not restored after restart
@NonCPSNo CPS transform; steps cannot be called
sh(script: '…', returnStdout: true).trim()Heavy work goes to the agent
jcli safe-restartGraceful restart
agent / environment / when (M3)
agent { docker { image 'python:3.13-slim'; label 'linux && docker' } }Container agent
REG = credentials('registry-creds')REG / REG_USR / REG_PSW
params.PUSH_IMAGEBoolean parameters (do not use env)
when { changeRequest target: 'main' }PR build
when { buildingTag() } / tag 'v*'tag build
when { triggeredBy 'TimerTrigger' }Scheduled trigger
Parallel and result control (M4)
failFast true / parallelsAlwaysFailFast()Fail fast
matrix { axes { axis { name 'PY'; values '3.12','3.13' } } … }Matrix
catchError(buildResult: 'SUCCESS', stageResult: 'UNSTABLE') { }stage yellow, build unchanged
warnError('msg') { } / unstable('msg')UNSTABLE
retry(count: 2, conditions: [agent()]) { }Infrastructure retry
timeout(time: 3, unit: 'MINUTES', activity: true) { }No-output timeout
Files (M5)
stash name: 'x', includes: 'reports/*.xml' / unstash 'x'Pass small files within one build
options { preserveStashes(buildCount: 3) }Preserved for Restart from Stage
archiveArtifacts artifacts: 'reports/**', fingerprint: trueArchive + fingerprint
junit testResults: 'reports/*.xml', allowEmptyResults: falseTest reports
cleanWs() / deleteDir()Clean the workspace
Docker (M6)
docker.build('myapp:1.1', '--label k=v .')Build
docker.withRegistry('http://localhost:3000', 'registry-creds') { img.push() }Push
docker.image('redis:7-alpine').withRun('--network-alias redis') { c -> }Dependency services
docker.image('python:3.13-slim').inside('-e HOME=/tmp') { sh '…' }Scripted container agent
reuseNode truestage-level docker agent reuses the outer node
Multibranch / Gitea (M7)
http://jenkins:8080/gitea-webhook/postWebhook endpoint
GITEA__webhook__ALLOWED_HOST_LIST=privateallow private addresses (already set in Lesson 1)
BRANCH_NAME · CHANGE_ID · CHANGE_TARGET · CHANGE_BRANCHbranch / PR variables
…/job/myapp-multibranch/indexing/consoleTextscan log
Trust: Nobody / Contributors / Everyonefork PR trust
jenkins-cli and REST
jcli declarative-linter < JenkinsfileValidate
jcli build JOB -p K=V -s -vBuild and output logs
jcli console JOB N -fFollow logs
jcli replay-pipeline JOB -n N < fileCLI Replay
jcli create-job NAME < job.xml / delete-jobManage jobs
jcli create-credentials-by-xml system::system::jenkins _ < c.xmlCreate credentials
/queue/api/json?tree=items[why,task[name]]Queue reason
/job/X/lastBuild/testReport/api/jsonTest statistics

Comprehensive lab + final quiz

Start from a new service repository and independently deliver a Multibranch pipeline that passes the review
about 40 minLocal · no cost

Scenario

The team has created a new service repository lab/myapp-worker (you can fork or copy it directly, lab/myapp as the starting point). Requirements: PRs must run Python 3.12/3.13 tests and write status back; the main branch builds the image and runs a smoke test; push happens only on main, when checked manually; fork PRs must not modify the pipeline; the whole pipeline finishes within 10 minutes on the two executors of agent1.

Create the repository: In Gitea, use lab/myapp as the template to create lab/myapp-worker (or git push a copy), and confirm that the Jenkinsfile is the final Module 8 version.
Multibranch: Create myapp-worker Multibranch job (Gitea source,gitea-myapp, three Discover traits, fork Trust = Contributors, orphaned items kept for 7 days).
Webhook: Use the Gitea API to register http://jenkins:8080/gitea-webhook/post, Test Delivery returns 200.
Execution model: For this build-and-test pipeline, add durabilityHint('PERFORMANCE_OPTIMIZED'), and record the rationale in the review notes; while the build is running, run jcli safe-restart, then confirm the build resumes.
PR flow: Open a PR that changes a test, and confirm that the PR-n build runs only up to Reports, Push is skipped, and the Gitea PR page shows the status.
main flow: Merge the PR and confirm that the main build triggers automatically; then, with PUSH_IMAGE=true a manual build once (if the push environment is not ready, record the reason).
Review: Score with the Module 8 scorecard (target ≥ 85), and turn unmet items into to-dos.
Cleanup:
cd ~/jenkinslab
jcli delete-job myapp-worker          # job for the integrated lab; myapp-multibranch is kept for later lessons
docker image ls 'myapp' --format '{{.Repository}}:{{.Tag}}' | grep -v -E '^myapp:1\.[01]$' | xargs -r docker image rm
docker network ls --filter name=smoke- -q | xargs -r docker network rm
docker compose stop                   # if you continue with Lesson 3, only stop; do not use down -v

Do not delete myapp:1.0/myapp:1.1 (used in later lessons). docker compose down -v Running this deletes the jenkins_home volumes, that is, all jobs, credentials, and build records.

Acceptance checklist

Open-ended self-test (6 questions)

1. Why does parsing a 50 MB JSON in a Jenkinsfile affect every team's builds?

Groovy runs on the controller,readFile/JsonSlurper it loads the content into controller heap memory, and CPS interpretation is slow and ties up CPS VM threads and GC; this should be done on the agent using jq and return only a small result.

2. If the controller is killed with kill -9, what happens to builds using PERFORMANCE_OPTIMIZED versus MAX_SURVIVABILITY?

The former may not be recoverable (state was not saved in time); the latter recovers from program.dat and FlowNodes and keeps reading the logs of durable tasks still running on the agent. With a graceful shutdown, both can be recovered.

3. The same when { branch 'main' }, why is it false in myapp but true in Multibranch?

The branch condition reads BRANCH_NAME (when empty, falls back to GIT_LOCAL_BRANCH), only Multibranch sets BRANCH_NAME; regular jobs do not have GIT_LOCAL_BRANCH by default either.

4. Explain docker.inside why the process in the container is uid 1000 and HOME is /.

The plugin runs the container as -u <agent uid>:<gid> , so that workspace file ownership is consistent; the image's /etc/passwd has no such uid, so HOME falls back to /; the agent host's environment variables are not passed in.

5. What are stash, archiveArtifacts, and an image registry each suited for?

stash: small files shared across agents within the same build; archiveArtifacts: small artifacts that need long-term viewing or downloading (reports, digests); image registry / artifact repository: images and large binaries.

6. The Jenkinsfile of a fork PR comes from the target branch, so is it safe now?

Not entirely. The PR's source code (tests, build scripts) still runs and can read anything accessible on that agent; you need an isolated agent, no sensitive credentials bound, and push/deploy stages must exclude PRs.

Sources and version notes

Sources for the technical facts in this lesson (verified 2026-11-16)
TopicVerification resultSource (accessed 2026-11-16)
Jenkins versionLTS 2.580.2 (2026-10-28), 2.580.1 (2026-09-30); weekly 2.590; from 2.555.1 on, Java 21 or 25 is required (Java 17 is no longer supported)LTS Changelog · latestCore.txt
Official imagesjenkins/jenkins:2.580.2-jdk21 (used in Lesson 1),2.580.2-lts-jdk21,lts-jdk21,2.580.2-jdk25 etc. tags existDocker Hub jenkins/jenkins
Plugin versionsworkflow-cps 4403.v471713a_cea_19 (2026-11-02, requires 2.568.1); workflow-job 1624.ve973eb_34e031; pipeline-model-definition 2.2293.v6e7193cec599; workflow-durable-task-step 1479.v56e587f413a_7; docker-workflow 653.v2f2c08eff0ec; gitea 286.v0740a_413c1eb_; git 5.11.0; workflow-multibranch 842.v3a_b_59b_57b_e6e; branch-api 2.1303.v9f3b_95dc329d; junit 1463.v7508416a_349c (requires 2.589); pipeline-graph-view 1134.v63b_71c6f549b_ (requires 2.589); ws-cleanup 0.49; credentials-binding 728.v902a_273b_8947; workflow-aggregator 608.v67378e9d3db_1plugins.jenkins.io(plugin API)
CPS / best practicesGroovy always runs on the controller; readFile+JsonSlurper doubles memory use; Jenkins.instance is misuse; NotSerializableException and @NonCPS; Performance Optimized may mask serialization problemsPipeline Best Practices
CPS method mismatchprogram.dat,expected to call … but wound up catching …, and no steps may be called inside @NonCPSCPS Method Mismatches
DurabilityThree levels, default MAX_SURVIVABILITY, global/job/branch settings, take effect on the next runScaling Pipelines · Project Cheetah (durabilityHint example)
Declarative syntaxoptions list (including parallelsAlwaysFailFast, disableRestartFromStage, preserveStashes); stage-level options come before agent and when; five parameter types; when conditions and the precedence of beforeAgent/beforeInput/beforeOptions; matrix axes/excludes/notValues and cell directives; post condition orderPipeline Syntax
branch conditionreads BRANCH_NAME and falls back to GIT_LOCAL_BRANCH when empty; help text “Only works in Multibranch”Source code BranchConditionalScript.groovy,BranchConditional/help.html (pipeline-model-definition-plugin master)
Basic stepsstash (includes/excludes/allowEmpty/useDefaultExcludes; small files, discarded when the build ends); retry conditions agent()/nonresumable(); timeout activity; catchError/warnError/unstable/errorPipeline: Basic Steps
Docker Pipelineinside command sequence: docker run -t -d -u … -w … -v …:rw,z | --volumes-from … + cat; docker top -eo pid,comm check; docker exec --env; docker stop --time=1 + docker rm -f --volumes; strips host environment variables and PATH; “seems to be running inside container” detection and ENTRYPOINT hint; reuseNode, args, dockerfile, withRun, withRegistry, Docker LabelUsing Docker with Pipeline; source code WithContainerStep.java,client/DockerClient.java (docker-workflow-plugin master)
Gitea pluginWebhook endpoint /gitea-webhook/post, based on X-Gitea-Event; Gitea Server's serverUrl, aliasUrl, manageHooks; credentials support username/password and PAT; traits names and options (Discover branches / PRs from origin / forks; Trust Nobody/Contributors/Everyone); commit status description and context; since Gitea 1.16.9, write permission is required; no Webhook secret validation found in the sourceGitea plugin page; source code GiteaWebhookAction.java,servers/GiteaServer.java,*DiscoveryTrait.java,Messages.properties,GiteaNotifier.java (gitea-plugin master)
Gitea Webhook host restrictions[webhook] ALLOWED_HOST_LIST Only external addresses are allowed by default; can be set to loopback/private/external/*, CIDR, or a hostnameGitea Config Cheat Sheet
Pipeline Graph ViewNew pipeline visualization, April 2026 plugin of the month; Stage View is still availableJenkins blog · Plugin page

Video verification note

The titles and channels of the videos below were verified via the YouTube oEmbed endpoint (2026-11-16): CloudBeesTV “What Is durabilityHint in Jenkins” (MkTEpYb7OBE), “What Is disableResume in Jenkins” (mkhMSohpKyc), “What Is the Difference Between Scripted and Declarative Pipeline” (GJBlskiaRrI), “How To Restart a Jenkins Pipeline From a Stage” (-7POl-vMLCQ), “What Does disableRestartFromStage Mean in Jenkins” (kBakPJHv6RU), “The Correct Way to Handle Credentials in a Jenkins Pipeline” (yfjtMIDgmfs), “Simplifying Parallel Pipeline Creation in Jenkins” (HsvO2nDlDSI), “What Is stash and unstash in Jenkins?” (0GQZzLlnUws), “Where Does Jenkins Store Archived Artifacts?” (u6LF-T-daS4), “How to Find Jenkins Workspace Directory in Linux” (0SR08akM5C4), “How to Setup Docker Containers As Build Agents for Jenkins” (ymI02j-hqpU), “How to Use Jenkins to Build and Run an Image Using Docker” (nfLO5ONVI6E), “How to Create a Gitea Organization in Jenkins” (NO3sZWRxgQM), “Jenkins Multibranch Pipeline With Git Tutorial” (B_2FXWI6CWg), “How to Create a GitHub Branch Source Multibranch Pipeline in Jenkins” (aDmeeVDrp0o); TechWorld with Nana “Complete Jenkins Pipeline Tutorial | Jenkinsfile explained” (7KCS70sCoK0), “Create Multibranch Pipeline with Git - Jenkins Pipeline Tutorial for Beginners 2/4” (tuxO7ZXplRE), “Jenkinsfile - Jenkins Pipeline Tutorial for Beginners 3/4” (MY1w7sWW5ms); Extreme Automation - Kamal Girdher “#5 … Declarative vs scripted Syntax” (1TAFteHZ4yY), “#11 … Parallel stages” (PjGEgaW8nRY), “#15 … Parameters” (VUsWrLQN2oY), “#21 … Docker Agent (3 use cases)” (cViyCxDEquo); Maximum Automation “Jenkins Conditional Stages Explained | Declarative Pipeline Tutorial with Live Examples” (04pbh22LIXo). oEmbed does not return durations or publish dates, so no durations are shown on the cards; some videos were recorded on earlier versions, so the UI may differ. No verified dedicated videos were found for CPS internals, Declarative matrix, or the CI readiness review, so storyboard scripts are provided instead.

Voice narration note

The “Voice” tab reads the narration aloud using the browser's Web Speech API (en-US); English terms are pronounced with en-US, and results depend on the system voice packs. This courseware does not embed MP3; for offline audio, pass the narration script to a TTS service to generate it.

Known limitations

  • The lab commands were not actually run in the environment that generated this courseware; the times, hashes, build numbers, container names, and test counts in the “expected output” are sample values, and log wording depends on your Jenkins and plugin versions (especially Resuming-related logs, the queue why text, and Gitea errors).
  • This lesson depends on the environment conventions from Lesson 1 (service names, ports, labels, credentials, repositories). This lesson builds on the post-Lesson 1 state, written in ~/jenkinslab (jenkinslab/agent1:jdk21,agent1_work volume,gitea/gitea:28.4, job myapp,.secrets/ tokens), not run step by step in a real environment. If your Lesson 1 environment has changed, follow the results of the pre-class checks in steps 1–5.
  • myapp's test content,/healthz response body, whether it reads LOG_LEVEL follow the Docker lesson's implementation; if tests need Redis, switch to withRun to provide Redis.
  • Pushing to the Gitea container registry depends on Gitea's packages feature and on ROOT_URL being reachable by the host Docker; Docker Desktop's networking may behave differently. This step is optional; Lessons 3 and 4 push to ACR/ECR.
  • The conclusion that the Gitea plugin does not validate the Webhook secret comes from searching the master branch source in 2026-11 (no related code found); later versions may add it, so check the plugin release notes.
  • The latest JUnit and Pipeline Graph View require the weekly core (2.589+); LTS users will get compatible earlier versions from the update center, so UI details may differ slightly.
  • The animations are simplified simulations of the real mechanisms: the CPS animation omits the batching details of FlowNode writes; the docker.inside animation omits the Windows branch and image-pull authentication details.