Jenkins Hour 2: Pipeline Core
~/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- Explain the Pipeline’s execution model: the Jenkinsfile is CPS-transformed, then interpreted on controller the controller,
shsteps such as these run via durable task on agent the agent; state is written toprogram.datand FlowNodes, so the controller can recover after a restart; understandNotSerializableException,@NonCPSand 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(includingcredentials()),parameters,options,when(includingbeforeAgent), and predict whether a stage will run and where it runs. - Use
parallel,matrix,failFast,catchError/unstableto organize stages, shortening feedback without hiding failures. - Distinguish workspace, stash, archived artifacts, fingerprints by lifecycle and use case, and use
junit,archiveArtifacts,cleanWsto manage outputs. - Use the Docker Pipeline plugin on
linux dockeragent1 to run a containerized agent (agent { docker }/docker.inside), build and smoke-testmyappimage, and explaindocker run … cat+docker exec’s real mechanism and the security cost of the Docker socket. - Connect
lab/myappto Multibranch Pipeline: Gitea branch source,http://jenkins:8080/gitea-webhook/postWebhook, PR builds (PR-1,CHANGE_ID), fork PR trust policy, and complete a CI readiness review.
1-hour time allocation
| # | Time | Module | Core content | Animation / interaction | Lab (~/jenkinslab) |
|---|---|---|---|---|---|
| 0 | Before class | Bridge & warm-up | Start 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 volume | Environment self-check list | jcli: check plugins and agent1 |
| 1 | 00–06 | Pipeline Architecture: CPS, Groovy and Persistence | CPS transform, Groovy on the controller, durable task on agents, program.dat, resume, durability, NotSerializableException, @NonCPS, sandbox | Core animation: CPS execution and persistence (including restart recovery and serialization failures) | Restart the controller and observe recovery; deliberately trigger NotSerializableException |
| 2 | 06–13 | Declarative and Scripted Syntax | pipeline/stages/steps/post vs node/stage, script block, validation timing, Replay, Restart from Stage, directive generator | Syntax comparator: click a structure to see both forms | Write the same flow twice and compare |
| 3 | 13–21 | agent, environment, parameters and when | agent none/label/docker, environment and credentials(), five parameter types, options, when conditions and beforeAgent | when evaluator: branch/parameter/trigger → which stages run | Parameterized myapp pipeline |
| 4 | 21–28 | Parallel, matrix and stage control | parallel, failFast, parallelsAlwaysFailFast, matrix axes/excludes, catchError/unstable/warnError, retry/timeout | Parallel timeline: failFast and exclude toggles | Python 3.12/3.13 matrix tests |
| 5 | 28–35 | Artifacts, stash and workspace management | workspace @2/@tmp, stash/unstash, archiveArtifacts, fingerprint, junit, buildDiscarder, cleanWs, preserveStashes | File flow: workspace ↔ stash ↔ artifact repository | Test reports + artifact archiving + stash across agents |
| 6 | 35–42 | Docker builds and containerized agents | agent docker/dockerfile, reuseNode, docker.inside mechanics, -u uid:gid, --volumes-from, docker.build/withRun/withRegistry, socket risks | docker.inside command-by-command animation | Build myapp image + redis smoke test |
| 7 | 42–50 | Multibranch, Webhooks and PR builds | branch source and Jenkinsfile discovery, Gitea Server configuration, Webhooks, PR head/merge, fork trust, BRANCH_NAME/CHANGE_*, commit status | Event flow: push / PR / fork PR | myapp Multibranch + Gitea Webhook + PR |
| 8 | 50–60 | CI readiness review and common failures | Review checklist, common errors, Replay and Restart from Stage debugging, interactive troubleshooting tree | Readiness scorecard + troubleshooting tree | Fault injection and fixes |
| — | After class | Cheat sheet · Capstone lab | Deliver a myapp Multibranch pipeline that passes review | Final quiz (12 questions) | Capstone lab |
Knowledge Coverage Matrix
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key syntax / commands | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Explain CPS execution and persistence | ✓ | ✓ | · | · | · | · | · | ✓ | durabilityHint,@NonCPS | M1 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.X | Parameterized pipeline |
| Conditional execution: when | · | · | ✓ | ✓ | · | ✓ | ✓ | ✓ | when { branch 'main'; beforeAgent true } | M3 / M7 |
| Parallel and matrix | · | · | · | ✓ | ✓ | · | · | ✓ | parallel,matrix,failFast | Python version matrix |
| Artifacts, test reports, stash | · | · | · | ✓ | ✓ | ✓ | · | ✓ | junit,archiveArtifacts,stash | M5 |
| Containerized builds and images | · | · | ✓ | ✓ | · | ✓ | · | ✓ | agent { docker },docker.build | myapp image smoke test |
| Multibranch / Webhook / PR | · | · | ✓ | · | · | · | ✓ | ✓ | /gitea-webhook/post,CHANGE_ID | M7 PR builds |
| Troubleshooting and review | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | Replay, Restart from Stage, Pipeline Graph View | M8 fault injection |
Topics not covered in this lesson (and where to learn them)
| Topic | Why it is not in this lesson | Where to learn it |
|---|---|---|
| controller/agent/executor/queue basics, setup wizard, plugin system, first Jenkinsfile, credentials basics | Covered in Lesson 1 | Lesson 1 |
| Pushing to ACR/ECR, deploying to Container Apps/AKS/ECS/EKS, cloud identity | Belongs to “Moving to the Cloud” | Lesson 3 (Azure),Lesson 4 (AWS) |
| Shared Libraries, JCasC, Job DSL, dynamic Pod agents with the Kubernetes plugin | Belongs to “Configuration as Code and Jenkins on Kubernetes” | Lesson 5 |
| Authorization strategies, Script Security approval process, supply chain and auditing | Belongs to enterprise security governance | Lesson 6 |
| Builds stuck in the queue, controller performance, thread dumps and GC analysis | Requires first understanding this lesson’s execution model | Lesson 7 · Lesson 8 (questions & interviews) |
| Writing Dockerfiles, multi-stage builds, image slimming | Knowledge about containers themselves | Docker 8 hours |
| Equivalent syntax in GitHub Actions / Azure Pipelines | This lesson only mentions it in a comparison table | GitHub course · Azure DevOps course |
How to use this courseware
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.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).
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.
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)
~/jenkinslab)
- Compose project
jenkinslab(~/jenkinslab/compose.yaml) three services:jenkins(jenkins/jenkins:2.580.2-jdk21,127.0.0.1:8080and127.0.0.1:50000, volumejenkins_home);agent1(self-built imagejenkinslab/agent1:jdk21, based onjenkins/inbound-agent, with python3 and docker CLI, inbound connection, keys in.env’sAGENT1_SECRET, viaDOCKER_GIDaccess to the mounted hostdocker.sock, working-directory volumeagent1_work:/home/jenkins/agent, 2 executors, labellinux docker);gitea(gitea/gitea:28.4, sqlite,127.0.0.1:3000,ROOT_URL=http://localhost:3000/, already setGITEA__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 userlab’s token (scopewrite:repository) is in~/jenkinslab/.secrets/gitea-token; credentialsgitea-myapp(username lab + token). - private repository
lab/myapp(Jenkins accesses it viahttp://gitea:3000/lab/myapp.gitaccess), local working copy~/jenkinslab/myapp:app.py(Flask + gunicorn, port 5000,/healthzreturns{"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 1Jenkinsfile(Test → Build imagemyapp:1.0/myapp:$BUILD_NUMBER→ Smoke test → Archive). - Jenkins job
myapp(Pipeline script from SCM), the one defined in Lesson 1jclifunction, exported~/jenkinslab/plugins.txt.
/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 ID | Purpose | Source |
|---|---|---|
docker-workflow (Docker Pipeline) | agent { docker },docker.inside/build/withRun/withRegistry | Installed in Lesson 1 Module 3 |
gitea | Gitea branch source, Webhook endpoint /gitea-webhook/post, commit status write-back | Installed in Lesson 1 Module 3 |
pipeline-graph-view,ws-cleanup,timestamper,junit,workflow-aggregator | visualization,cleanWs(),timestamps(), test reports, the Pipeline suite | Recommended 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.
Module 1 · Pipeline Architecture: CPS, Groovy and Persistence
- 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,timeouttiming, 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) anddisableResume(). - Understand why the Groovy sandbox (Script Security) rejects
Jenkins.instanceand similar calls.
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 / step | Where it runs | Notes |
|---|---|---|
if, loops, string concatenation,def variables, custom methods | controller (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 timing | controller | step implementations run inside the controller JVM; stash ’s file packaging/transfer involves both the agent and the controller. |
node / agent | Started by the controller, occupies the agent’s executor | Requests 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 / powershell | agent | Executed 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,dir | the agent’s file system, with results returned to the controller | readFile 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
inputwhile 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 agentmake testkeep 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
- Local variables must be serializable. When calling
sh,sleep,inputor other async steps, every variable still in scope gets written intoprogram.dat.java.util.regex.Matcher,groovy.json.internal.LazyMap(JsonSlurper’s result), iterators, network connections, etc. are not serializable →java.io.NotSerializableException. @NonCPSMethods 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,echoetc.), otherwise behavior is abnormal; if interrupted, it re-runs from the beginning.- 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-ifiedtoString(). The log shows aexpected to call … but wound up catching …warning. - 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 asjq,curl).
durability levels (Speed/Durability Settings)
| Level | Write method | After a controller crash (abnormal shutdown) | Best for |
|---|---|---|---|
MAX_SURVIVABILITY (default) | Every step atomically writes FlowNode and program state | Can resume | Deployments and pipelines with input approval steps (critical pipelines) |
SURVIVABLE_NONATOMIC | Writes each step, but without atomic writes | Usually resumable; a small chance of data loss on OS crash | On network file systems JENKINS_HOME |
PERFORMANCE_OPTIMIZED | Greatly reduces disk I/O, saves only at key moments | May not be resumable, running builds fail or lose some records; a graceful shutdown (safe-restart) still allows resume | Official 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, orRejectedAccessException. - 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-restartto let running pipelines save to disk before stopping.
Comparison with similar technologies
| Jenkins Pipeline | GitHub Actions | Azure Pipelines | |
|---|---|---|---|
| Process definition | Groovy DSL (Declarative/Scripted), interpreted on the controller | YAML, orchestrated by the server | YAML, orchestrated by the server (templates expanded at queue time) |
| Step execution | durable task on the agent | process on the runner | task on the agent |
| Orchestration service restart | CPS state saved to disk, resumable | Managed service, invisible to users | Managed service, invisible to users |
| Arbitrary code logic | Yes (Groovy, subject to sandbox restrictions) | Expressions + script steps | Expressions + script steps |
For comparison details, see GitHub courseand Azure DevOps course.
@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
Sequence: one sh call and one restart
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+)/).
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 / command | Purpose | Notes |
|---|---|---|
options { durabilityHint('PERFORMANCE_OPTIMIZED') } | Set this job’s durability | Takes effect on the next run; can also be set on the job configuration page |
options { disableResume() } | Not resumed after controller restart; fails directly | Suitable for non-idempotent steps whose state after recovery cannot be trusted |
@NonCPS def f(...) { ... } | Method is not CPS-transformed | Only 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 output | Replaces 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-restart | Wait for running steps to reach a savepoint, then restart | Web UI: /safeRestart |
jcli console JOB [N] -f | Follow console output in the terminal | After restart you will see Resuming-related logs |
| Manage Jenkins → System → Pipeline Speed/Durability Settings | Global default level | When unset, it is MAX_SURVIVABILITY |
| Manage Jenkins → In-process Script Approval | View signatures rejected by the sandbox and awaiting approval | Lesson 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)
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-labsleep 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.
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.
// 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}"
}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.
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
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
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
- Pipeline Best Practices
- Pipeline CPS Method Mismatches
- Scaling Pipelines (Speed/Durability Settings)
- Pipeline: Groovy plugin
- Pipeline: Nodes and Processes plugin
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.
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.
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.
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.
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.
Module 2 · Declarative and Scripted Syntax
- 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([...]),parallelmap. - Use
declarative-linterto 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.
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
| Capability | Declarative | Scripted |
|---|---|---|
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 in | Must 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 / section | pipeline top level | Inside stage | Notes |
|---|---|---|---|
agent | Required (can be none) | Optional | Top level agent none (then each stage must declare its own) |
stages / steps | stages Required | steps,stages,parallel,matrix pick one of four | Nested 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 callparallel. - 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-syntaxpage, choose a step, fill in the form, and generate the step code (such aswithCredentials,checkout). - Declarative Directive Generator: on the left side of the same page, generate
agent,options,when,parametersand other directives. - Global Variable Reference:
env,params,currentBuild,scm,dockeretc. 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.
${} 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
Declarative structure tree
Interactive: syntax comparator
Click a requirement; the left and right sides show the Declarative and Scripted forms, with the differences explained.
Syntax and tool commands
| Command / address | Purpose | Notes |
|---|---|---|
jcli declarative-linter < Jenkinsfile | Validate Declarative structure on the server side | Use 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/validate | Validate via HTTP | Can be placed in a Git pre-commit hook |
http://127.0.0.1:8080/job/<job>/pipeline-syntax/ | Snippet Generator / Directive Generator | Generated code matches the current plugin version |
…/pipeline-syntax/globals | Global variable reference | env,currentBuild,docker etc. |
| build page → Replay | Edit the script and run again | Requires Job/Configure or Run/Replay permission |
| build page → Restart from Stage | Rerun from a top-level stage | Declarative only; options { disableRestartFromStage() } can be disabled |
jcli replay-pipeline JOB -n N < Jenkinsfile | CLI Replay | standard 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)
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.
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.
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.
steps { to step {, run the linter and see Unknown stage section "step", then change it back (do not commit the broken version).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().
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}"
}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
Official documentation
- Pipeline Syntax
- Pipeline Development Tools (linter, Replay)
- Snippet Generator
- Running Pipelines (Restart from Stage)
Video storyboard (about 80 s)
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.
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.
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.
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.
Module 3 · agent, environment, parameters and when
- Choose agents for myapp: top-level
agent none+ stage levellabel/docker, and understand that each stage with its own agent is allocated an executor separately and performs an implicit checkout. - Use
environmentto define variables, and usecredentials()to bind credentials (_USR/_PSWsuffix), and avoid leaking secrets through Groovy interpolation. - Use
parameterswith its five types (string/text/booleanParam/choice/password) to parameterize builds, and understand why “parameters only appear after the first run”. - Use
whenwith its built-in conditions (branch/tag/buildingTag/changeRequest/changeset/environment/expression/triggeredBy/not/allOf/anyOf) to control stages, and usebeforeAgent trueto avoid allocating agents for skipped stages.
agent: where it runs
| Syntax | Meaning | Use in myapp |
|---|---|---|
agent any | Any available node | Not recommended: it may run on an unsuitable node |
agent none | Top level does not allocate; each stage declares its own | Top-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 customWorkspace | Rarely 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 container | Unit 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 agent | When the toolchain needs customization |
agent { kubernetes { yaml '…' } } | Kubernetes plugin creates Pods dynamically | Lesson 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
environmentapplies 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 areGIT_COMMIT,GIT_BRANCH; in Multibranch there areBRANCH_NAME,CHANGE_IDetc. (Module 7). credentials('id')Binding by credential type:
| Credential type | FOO = credentials('id') Gives |
|---|---|
| Secret text | FOO = text |
Username with password (such as gitea-myapp,registry-creds) | FOO = username:password,FOO_USR,FOO_PSW |
| Secret file | FOO = temporary file path |
| SSH Username with private key | FOO = 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
| Type | Example | Read as |
|---|---|---|
string | string(name: 'IMAGE_SUFFIX', defaultValue: '', description: 'Extra tag suffix') | params.IMAGE_SUFFIX |
text | Multi-line text | params.NOTES |
booleanParam | booleanParam(name: 'PUSH_IMAGE', defaultValue: false, description: 'Push image') | params.PUSH_IMAGE (boolean) |
choice | choice(name: 'PY', choices: ['3.13', '3.12']) | The first option is the default value |
password | Password entered at run time | Not 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
| Condition | Example | Note |
|---|---|---|
branch | branch '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 builds | Multibranch needs Discover tags enabled |
changeRequest() | changeRequest target: 'main' | PR builds (CHANGE_ID exists) |
changeset | changeset 'app/**' | based on the changeset of this build; the changeset is empty on the first build |
environment / equals | environment name: 'DEPLOY', value: 'true' | String comparison |
expression | expression { params.PUSH_IMAGE } | Groovy returns true or false; null is treated as false |
triggeredBy | triggeredBy 'TimerTrigger',triggeredBy cause: 'UserIdCause' | distinguishes scheduled / manual / SCM |
not / allOf / anyOf | allOf { 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'.
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
Agent layout of the myapp pipeline in this lesson
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' }
}
}
}
| Command | Purpose |
|---|---|
jcli build myapp -p PUSH_IMAGE=true -p LOG_LEVEL=DEBUG -s -v | Build with parameters |
jcli get-job myapp | grep -A3 ParameterDefinition | Confirm the parameters are written to the job configuration |
jcli create-credentials-by-xml system::system::jenkins _ < cred.xml | Create credentials in the global domain |
jcli list-credentials system::system::jenkins | List credential IDs (without showing secrets) |
http://127.0.0.1:8080/env-vars.html | List 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)
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.
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).
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.
Running on agent1 for it. Temporarily remove beforeAgent true and run it again with Replay to compare the extra agent allocation and checkout.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).
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
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
Official documentation
- Pipeline Syntax: agent / environment / parameters / when
- Using a Jenkinsfile: Handling credentials
- String interpolation
Video storyboard (about 90 s)
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.
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.
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.
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.
Module 4 · Parallel, matrix and stage control
- Write the Declarative
parallelandmatrix(axes/axis/excludes/ cell levelagent), 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,errorto precisely set the stage and build results; useretry(includingconditions: [agent()]) andtimeout(includingactivity: 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.
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 truethen aborts the remaining branches at the first failure (saving executors).
How: toolbox for controlling stage results
| Step / option | Effect | Typical use |
|---|---|---|
catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') { … } | Catches errors, sets the build and stage result according to the parameters, and continues with subsequent stages | When 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 UNSTABLE | Lint warnings |
unstable('msg') | Sets the build and stage to UNSTABLE | Coverage 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 agent | network jitter, temporary agents |
timeout(time: 10, unit: 'MINUTES') { … } / timeout(time: 3, unit: 'MINUTES', activity: true) | Absolute timeout / no-output timeout | Hung tests |
options { skipStagesAfterUnstable() } | Build becomes UNSTABLE and subsequent stages are skipped | Do not push images when tests are flaky |
options { parallelsAlwaysFailFast() } | Parallel/matrix blocks default to failFast | Environments 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
shand other external processes actually run in parallel. - Too many matrix combinations make the generated code too large (you may hit
Method code too largeand 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).
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
Result combination rules
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
| Syntax | Description |
|---|---|
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)
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.
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.
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.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', …).
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'
}
}
}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
Declarative matrix dedicated video: No verified video found; refer to the official documentation and this module's animations.
Official documentation
- Pipeline Syntax: Parallel
- Pipeline Syntax: Matrix
- Basic Steps: catchError / warnError / retry / timeout
Video storyboard (about 80 s)
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.
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.
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.
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.
Module 5 · Artifacts, stash and workspace management
- Describe the workspace (workspace),
@2/@tmpdirectories, stash, archived artifacts, and fingerprints: where each is stored and when it is deleted. - Use
stash/unstashto 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
junitto publish test reports,archiveArtifacts(includingfingerprint,allowEmptyArchive) to archive artifacts,buildDiscarderto 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”.
What: four “destinations for files”
| Location | Lifecycle | Suitable for | Not suitable for | |
|---|---|---|---|---|
| Workspace | agent: <Remote root>/workspace/<job>; when concurrent, @2,@3; temp files live in @tmp | are kept by default after the build ends, and reused in the next build (incremental checkout) | Intermediate files during the build | Passing across agents; serving as a trusted “clean environment” |
| stash | controller: 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 Stage | Passing 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 artifacts | controller: 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 cleanup | Reports, manifests, small release packages, image digests | Large binaries (should be published to an artifact repository / image registry) |
| Fingerprints | controller: $JENKINS_HOME/fingerprints/ (MD5) | independent of build records | Tracks “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 buildjunitread old reports and create a “false success”. - The controller's
JENKINS_HOMEdisk is expensive: stashes and artifacts are both written here, and large files slow backups and can exhaust the disk.
How: key steps
| Step | Key parameters | Description |
|---|---|---|
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: false | excludes,onlyIfSuccessful | Fails by default when the pattern matches nothing (to prevent silent omissions) |
junit testResults: 'reports/*.xml', allowEmptyResults: false | skipPublishingChecks 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.
How files flow within one build
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
| Command | Purpose |
|---|---|
docker compose exec jenkins ls /var/jenkins_home/jobs/myapp/builds/7/archive/reports | See 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.txt | Download 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/*/builds | Check 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)
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”.
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.
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.
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’.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.
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
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
Official docs
- Pipeline: Basic Steps (stash / unstash / deleteDir)
- Core steps (archiveArtifacts / fingerprint)
- JUnit plugin
- Workspace Cleanup plugin
Video storyboard (about 80 s)
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.
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.
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.
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.
Module 6 · Docker builds and containerized agents
- Use
agent { docker { … } },agent { dockerfile { … } },reuseNode true,args(cache volume), and Scripteddocker.image().inside,docker.build,withRun,withRegistry. - Based on the plugin source, walk through
insidethe real command sequence:docker run -t -d -u uid:gid -w ws -v …/--volumes-from … image cat→docker topValidate → each stepdocker 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.
What: two ways of “building in Docker”
| containerized agent (run steps inside a container) | build an image (producing a container image) | |
|---|---|---|
| Syntax | agent { docker { image 'python:3.13-slim' } },docker.image('…').inside { },agent { dockerfile true } | sh 'docker build …',docker.build('myapp:1.1'),image.push() |
| Purpose | Decouple the toolchain from the agent: agent1 does not need Python 3.12/3.13 installed | The deliverable is the image |
| Dependencies | The 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)
- Check whether the image exists (
docker inspect), and if it does not,docker pull(alwaysPull truewhen set, always pulls). - 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, printdoes not seem to be running inside a container, and use-v workspace:workspace:rw,zbind mount. docker run -t -d -u 1000:1000 [args] -w <workspace> -v …|--volumes-from … -e ******** … <image> catRuns as the agent user's uid:gid starts acatprocess 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 andPATHare removed.docker top <id> -eo pid,comm: confirm the container is really runningcat. If the image's ENTRYPOINT swallows the command arguments, you will getThe container started but didn't run the expected command, so it is recommended to add--entrypoint=''.- Each
shturns intodocker exec --env … <id> …(the durable task wrapper still works, and logs are still written under the workspace's@tmpso the controller can still recover after a restart). - 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 -gfails with Permission denied → use a venv or a directory inside the project, orenvironment { HOME = "${WORKSPACE}" }. - The image must have
catandsh: 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/agentonagent1_worka 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 trueLet 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
| Scenario | Pattern |
|---|---|
| One toolchain for the whole pipeline | Top level agent { docker { image …; label 'linux && docker' } } |
| Different toolchains in different stages | Top level agent none + stage-level docker agent (this lesson) |
| Toolchain needs customization | agent { 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 Kubernetes | Kubernetes plugin Pod agent (Lesson 5); the Docker Pipeline inside is unavailable in Pods without a Docker daemon |
Security trade-offs of image builds
| Option | Isolation | Notes |
|---|---|---|
agent mounts the host /var/run/docker.sock (this lesson's lab) | Weakest: equivalent to host root | Only for personal labs or a dedicated, disposable build machine |
Dedicated Docker host / remote BuildKit (docker buildx remote driver) | Medium: isolated to a dedicated build machine | with TLS and network isolation |
| Rootless Docker / rootless BuildKit / Buildah | Stronger: does not require host root | Some features are restricted (ports, storage driver) |
| Kubernetes Pod agent + daemonless builder | Stronger (isolated per Pod) | Lesson 5; note that the original Google repository for kaniko is archived, so check its maintenance status when choosing |
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
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 Pipeline syntax
| Syntax | Notes |
|---|---|
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)
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" . 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).
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.
sh 'id; echo HOME=$HOME; pip install --user requests || true', and you will see uid=1000 gid=1000,HOME=/ and Permission denied.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.
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.
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
Official docs
- Using Docker with Pipeline
- Docker Pipeline plugin
- docker-workflow-plugin source (WithContainerStep, DockerClient)
Video storyboard (about 90 s)
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.
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.
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.
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.
Module 7 · Multibranch, webhooks and PR builds
- 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, repositorymyapp, credentialsgitea-myapp), and webhookhttp://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).
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 variables | Branch build | PR build |
|---|---|---|
BRANCH_NAME | main,feature/login | PR-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_TAG | myapp-multibranch/feature%2Flogin / jenkins-myapp-multibranch-feature%2Flogin-4 | myapp-multibranch/PR-3 |
Three configuration points of the Gitea plugin
- 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 payloadsROOT_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). - 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), Ownerlab, Repositorymyapp, and Behaviours (traits). - Webhook (Gitea repository → Settings → Webhooks → Gitea): Target URL
http://jenkins:8080/gitea-webhook/post, POST,application/json. The plugin uses theX-Gitea-Eventheader to handle push, create/delete, pull_request and other events.
Behaviours (traits)
| Trait (UI name) | Option | Recommended |
|---|---|---|
| Discover branches | Only 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 origin | Merging the pull request with the current target branch revision / The current pull request revision / Both | merge: 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 forks | Same as above + Trust: Nobody / Contributors / Everyone | Contributors 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 Multibranch | GitHub Actions | Azure Pipelines | |
|---|---|---|---|
| PR trigger | Webhook / scan | on: pull_request | PR triggers / build validation in branch policies |
| fork PR protection | trust policy + target-branch Jenkinsfile | pull_request no secrets, approval required to run | fork builds get no secrets by default |
| Status write-back | the plugin writes back commit status | native checks | native status |
Full path from webhook to commit status
head and merge PR revisions
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 / endpoint | Purpose |
|---|---|
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/consoleText | View the log of the latest scan |
jcli build 'myapp-multibranch/main' -p PUSH_IMAGE=true -s | Build a branch child job (with parameters) |
jcli list-jobs myapp-multibranch | List 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/post | Gitea 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/hooks | List 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)
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.
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.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.
myapp-multibranch → Multibranch Pipeline:
- Branch Sources → Add source → Gitea: Server
gitea-local, Credentialsgitea-myapp, Ownerlab, Repositorymyapp. - 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.
cd ~/jenkinslab/myapp jcli declarative-linter < Jenkinsfile && git commit -am "Lesson 2: branch-safe image tags" && git push jcli list-jobs myapp-multibranch
main
# 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.
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).
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).
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).
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
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
Official docs
- Branches and Pull Requests
- Gitea plugin
- Gitea configuration: [webhook] ALLOWED_HOST_LIST
- Tutorial: Build a multibranch Pipeline project
Video storyboard (about 90 s)
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.
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.
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.
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.
Module 8 · CI readiness review and common failures
- 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/consoleTextand Gitea Recent Deliveries to locate problems.
What: CI readiness review checklist (myapp version)
| Dimension | Check item | Covered in this lesson |
|---|---|---|
| Correctness | Declarative,declarative-linter passes | M2 |
each stage explicitly declares its agent (top-level agent none or an explicit label), and never builds on the Built-In Node | M3 | |
test reports come from this build (junit empty or stale reports are not allowed; a test failure fails the build | M5 | |
| artifact names are unique across branches (image tags, container names, network names) | M6, M7 | |
| Speed | independent checks run in parallel; the number of branches matches the number of executors | M4 |
skipped stages use beforeAgent true | M3 | |
build and test pipelines can consider PERFORMANCE_OPTIMIZED; disableConcurrentBuilds(abortPrevious: true) | M1, M3 | |
| Security | credentials are passed only through credentials()/withCredentials binding, single-quoted references, no Groovy interpolation warnings | M3 |
| push and deploy stages run only on main (not on PRs) | M3, M7 | |
| fork PR trust policy is not Everyone | M7 | |
| the Docker socket risk and the replacement plan are documented | M6 | |
| Maintainability | little 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 resources | timeout,timestamps(),buildDiscarder | M2, M5 |
| diagnostics printed on failure (application log, test report), artifacts downloadable | M5, M6 | |
| in post, clean up containers, networks, temporary images and the workspace | M5, M6 |
Why: classify first, then look at details
| Layer | Typical signal | Where to look first |
|---|---|---|
| Declarative validation | WorkflowScript: N: …, 0 steps executed | linter, Jenkinsfile line number |
| Groovy / CPS / sandbox | NotSerializableException,RejectedAccessException,MissingPropertyException | in 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 / container | docker: permission denied docker.sock, uid/HOME, empty workspace | agent logs,docker inspect |
| SCM / Webhook | no build, builds an old commit, PR does not appear | indexing logs, Gitea Recent Deliveries |
| the command itself | non-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/consoleTexteasy 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.
Error layer diagnosis
Final pipeline for this lesson
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
| Command | Purpose |
|---|---|
jcli declarative-linter < Jenkinsfile | Structure 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.groovy | CLI Replay |
jcli get-node agent1 / jcli list-jobs myapp-multibranch | labels and branch jobs |
docker compose logs --since 10m jenkins agent1 gitea | recent logs of the three services |
docker compose exec agent1 docker ps -a --filter status=exited | leftover 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)
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.
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"}'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.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.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.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.
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'
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
“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)
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.
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.
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.
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.
Command cheat sheet
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' } }
}options { durabilityHint('PERFORMANCE_OPTIMIZED') } | Performance first |
options { disableResume() } | Not restored after restart |
@NonCPS | No CPS transform; steps cannot be called |
sh(script: '…', returnStdout: true).trim() | Heavy work goes to the agent |
jcli safe-restart | Graceful restart |
agent { docker { image 'python:3.13-slim'; label 'linux && docker' } } | Container agent |
REG = credentials('registry-creds') | REG / REG_USR / REG_PSW |
params.PUSH_IMAGE | Boolean parameters (do not use env) |
when { changeRequest target: 'main' } | PR build |
when { buildingTag() } / tag 'v*' | tag build |
when { triggeredBy 'TimerTrigger' } | Scheduled trigger |
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 |
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: true | Archive + fingerprint |
junit testResults: 'reports/*.xml', allowEmptyResults: false | Test reports |
cleanWs() / deleteDir() | Clean the workspace |
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 true | stage-level docker agent reuses the outer node |
http://jenkins:8080/gitea-webhook/post | Webhook endpoint |
GITEA__webhook__ALLOWED_HOST_LIST=private | allow private addresses (already set in Lesson 1) |
BRANCH_NAME · CHANGE_ID · CHANGE_TARGET · CHANGE_BRANCH | branch / PR variables |
…/job/myapp-multibranch/indexing/consoleText | scan log |
| Trust: Nobody / Contributors / Everyone | fork PR trust |
jcli declarative-linter < Jenkinsfile | Validate |
jcli build JOB -p K=V -s -v | Build and output logs |
jcli console JOB N -f | Follow logs |
jcli replay-pipeline JOB -n N < file | CLI Replay |
jcli create-job NAME < job.xml / delete-job | Manage jobs |
jcli create-credentials-by-xml system::system::jenkins _ < c.xml | Create credentials |
/queue/api/json?tree=items[why,task[name]] | Queue reason |
/job/X/lastBuild/testReport/api/json | Test statistics |
Comprehensive lab + final quiz
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.
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.myapp-worker Multibranch job (Gitea source,gitea-myapp, three Discover traits, fork Trust = Contributors, orphaned items kept for 7 days).http://jenkins:8080/gitea-webhook/post, Test Delivery returns 200.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.PUSH_IMAGE=true a manual build once (if the push environment is not ready, record the reason).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.
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
| Topic | Verification result | Source (accessed 2026-11-16) |
|---|---|---|
| Jenkins version | LTS 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 images | jenkins/jenkins:2.580.2-jdk21 (used in Lesson 1),2.580.2-lts-jdk21,lts-jdk21,2.580.2-jdk25 etc. tags exist | Docker Hub jenkins/jenkins |
| Plugin versions | workflow-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_1 | plugins.jenkins.io(plugin API) |
| CPS / best practices | Groovy always runs on the controller; readFile+JsonSlurper doubles memory use; Jenkins.instance is misuse; NotSerializableException and @NonCPS; Performance Optimized may mask serialization problems | Pipeline Best Practices |
| CPS method mismatch | program.dat,expected to call … but wound up catching …, and no steps may be called inside @NonCPS | CPS Method Mismatches |
| Durability | Three levels, default MAX_SURVIVABILITY, global/job/branch settings, take effect on the next run | Scaling Pipelines · Project Cheetah (durabilityHint example) |
| Declarative syntax | options 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 order | Pipeline Syntax |
| branch condition | reads 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 steps | stash (includes/excludes/allowEmpty/useDefaultExcludes; small files, discarded when the build ends); retry conditions agent()/nonresumable(); timeout activity; catchError/warnError/unstable/error | Pipeline: Basic Steps |
| Docker Pipeline | inside 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 Label | Using Docker with Pipeline; source code WithContainerStep.java,client/DockerClient.java (docker-workflow-plugin master) |
| Gitea plugin | Webhook 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 source | Gitea 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 hostname | Gitea Config Cheat Sheet |
| Pipeline Graph View | New pipeline visualization, April 2026 plugin of the month; Stage View is still available | Jenkins 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_workvolume,gitea/gitea:28.4, jobmyapp,.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,
/healthzresponse body, whether it readsLOG_LEVELfollow the Docker lesson's implementation; if tests need Redis, switch towithRunto 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.