Jenkins Lesson 1: Core Fundamentals
docker compose up to your first green build: controller / agent / executor / queue, the setup wizard, plugins, job types, Jenkinsfile, credentials, and finally testing myapp, packaging it as an image and archiving it- Map out Jenkins’ runtime architecture: controller, agent, node, executor, queue (Queue), label, workspace, and
JENKINS_HOME, and be able to walk through every step of “one build from trigger to result” (this lesson’s core animation). - Set up a local lab environment with Docker Compose
~/jenkinslab: jenkins (controller,jenkins/jenkins:2.580.2-jdk21),agent1 (inbound agent, labellinux docker),gitea (local Git server, repolab/myapp). Lesson 2 continues directly on this environment. - Work through the setup wizard, and understand the difference between LTS and weekly, the Java 21/25 requirements, the plugins no longer bundled with the WAR from 2.580.1 onward, and why the built-in node should be set to 0 executors.
- Understand the plugin system: the Update Center offers compatible versions by core version, dependency resolution,
requiredCore, installation/upgrade/rollback, and usingplugins.txt+jenkins-plugin-clito pin plugin versions. - Distinguish Freestyle, Pipeline, Multibranch Pipeline, Organization Folder, and write your first Declarative Jenkinsfile (
agent/stages/steps/post/options). - Create and use credentials
gitea-myapp(Gitea username + access token), understand credential scope,withCredentialslog masking, and the “Groovy string interpolation leaking secrets” warning. - Run myapp as a full CI: pytest + JUnit report →
docker buildbuild themyapp:1.0→ smoke test/healthz→ archive the artifacts and add fingerprints; finally, check the environment with the 12-item readiness review and troubleshooting tree.
1-hour time allocation table
| # | Time | Module | Core content | Animation / interaction | Lab (~/jenkinslab) |
|---|---|---|---|---|---|
| 0 | Before class | Environment setup | compose.yaml (jenkins / agent1 / gitea), Gitea user lab and repo lab/myapp, myapp source and test push | Environment self-check checklist | Three containers running,lab/myapp code present |
| 1 | 00–06 | Jenkins architecture | controller / agent / node / executor / queue / label / workspace; built-in node with 0 executors; agent → controller security | Core animation: the lifecycle of a build | Create node agent1 and connect it |
| 2 | 06–13 | Installation and setup | LTS vs weekly, Java 21/25, image tags,JENKINS_HOME, initialAdminPassword, setup wizard, Jenkins URL | First startup and wizard sequence | Unlock, create admin, generate API token |
| 3 | 13–21 | Plugin system | Update Center, dependencies and requiredCore, suggested plugins, plugins split out in 2.580.1, security advisories, version pinning | Plugin dependency resolver | Install the Gitea and Docker Pipeline plugins, export plugins.txt |
| 4 | 21–28 | Job types | Freestyle, Pipeline, Multibranch, Organization Folder, folders; configuration stored in config.xml | Job type selector + branch indexing | Create a Freestyle comparison and a Pipeline job myapp |
| 5 | 28–35 | Your first Jenkinsfile | Declarative structure, agent label, stage/steps, options, environment, post condition order | Jenkinsfile line-by-line executor | Commit the Jenkinsfile and run your first green build |
| 6 | 35–42 | Credentials and security basics | Credential types and scopes, encrypted storage, withCredentials, masking, interpolation warnings, least-privilege tokens | Credential resolution and masking | Create gitea-myapp, and call the Gitea API securely |
| 7 | 42–50 | Build myapp | pytest + junit, docker build, smoke test, archiveArtifacts, fingerprint, UNSTABLE and FAILURE | Stage view simulator | Build the myapp:1.0 and archive the report |
| 8 | 50–60 | Readiness review and troubleshooting basics | 12-item build readiness review; stuck queue, agent offline, authentication failure, docker.sock permissions, test failure | Interactive troubleshooting tree | Deliberately create 4 faults and fix them |
| — | After class | Cheat sheet · Integrated lab | Turn manual configuration into a repeatable script and verify it | Final quiz (12 questions) | Integrated lab |
Knowledge Coverage Matrix
| Target skill | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands / UI | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Explain controller / agent / executor / queue | ✓ | · | · | ✓ | ✓ | · | ✓ | ✓ | /queue/api/json,/computer/api/json | M1, M8 |
| Docker installation and JENKINS_HOME management | · | ✓ | ✓ | · | · | ✓ | · | ✓ | docker compose,initialAdminPassword | Module 0, M2 |
| Connect and manage agents, labels | ✓ | ✓ | · | · | ✓ | · | ✓ | ✓ | jenkins/inbound-agent,-url … secret name | M1 |
| Plugin installation, dependencies and version pinning | · | ✓ | ✓ | · | · | · | · | ✓ | install-plugin,jenkins-plugin-cli | M3 |
| Choose job types, manage config.xml | · | · | · | ✓ | ✓ | · | ✓ | · | create-job,get-job | M4 |
| Write a Declarative Jenkinsfile | · | · | · | ✓ | ✓ | ✓ | ✓ | ✓ | declarative-linter,build -s -v | M5, M7 |
| Credential creation, binding and masking | · | · | · | ✓ | · | ✓ | ✓ | ✓ | withCredentials,create-credentials-by-xml | M6 |
| Test reports, image builds, artifact archiving | · | · | · | · | ✓ | · | ✓ | ✓ | junit,archiveArtifacts,docker build | M7, integrated lab |
| Build troubleshooting | ✓ | ✓ | ✓ | · | ✓ | ✓ | ✓ | ✓ | Console logs,docker compose logs, node logs | M8 troubleshooting tree |
What this lesson leaves out (and where to learn it)
| Topic | Why it is not in this lesson | Where to learn it |
|---|---|---|
| Multibranch hands-on, webhook triggers, parallel, matrix, Shared Library, CPS and persistence internals | Core Pipeline material | Lesson 2 |
| Pushing images to ACR / ECR, cloud credentials and managed identities | Requires a cloud subscription | Lesson 3 (Azure), Lesson 4 (AWS) |
| Configuration as Code (JCasC), deploying Jenkins with Helm, Kubernetes Pod agents | Requires first understanding every manual configuration item | Lesson 5 |
| SSO (OIDC/SAML/Entra), matrix/role authorization, Script Security approval | Belongs to enterprise security and governance | Lesson 6 |
| Performance tuning, thread dumps, queue depth troubleshooting, backup and restore drills | Belongs to advanced troubleshooting | Lesson 7 |
| Dockerfile best practices, multi-stage builds, image security scanning | Covered in the Docker course | Docker 8-hour course |
| GitHub Actions and Azure Pipelines themselves | Covered in other courses; this lesson only compares them | GitHub course · Azure DevOps course |
How to use this courseware
Theory · Diagram · Animation · Commands · Lab · Production case · Troubleshooting · Quiz · Voice · Video. We suggest reading “Theory” and “Animation” first, then doing the “Lab”. The “build lifecycle” animation in Module 1 is the core of this lesson, and every later module returns to it.
A quiz score of 70% or higher, or clicking “Mark this module complete”, counts toward progress, saved in this browser’s local storage (if the browser blocks local storage, it is cleared on refresh).
The “Voice” tab uses the browser’s built-in Web Speech API (en-US) to read the narration aloud; if no Chinese voice pack is installed, the narration script can still be read, or passed to a TTS tool to generate audio.
jenkins/jenkins:2.580.2-jdk21, the agent image is jenkins/inbound-agent:3395.v6e5377b_0fb_3c-5-jdk21, and Gitea is gitea/gitea:28.4 (starting with 28.0, Gitea dropped the “1.” prefix from its version numbers, so the former 1.28 is now 28.0). For plugin versions, follow the compatible versions the Update Center provides for 2.580.2 at install time (see Module 3). A new LTS baseline comes out roughly every 12 weeks; read the LTS upgrade guide.Module 0 · Environment setup (complete before class)
~/jenkinslab use Docker Compose to start the three services jenkins, agent1 and gitea, create the Gitea user lab and the private repo lab/myapp, and push the myapp source and tests- An Ubuntu 24.04 VM or workstation (recommended, consistent with the Docker course), or Docker Desktop on macOS / Windows 11 + WSL2. Available memory ≥ 4 GB, disk ≥ 15 GB.
- Installed Docker Engine 29 and Docker Compose v2 (
docker compose version), and the current user can rundocker. For installation instructions, see Docker course. - Installed Git 2.4x,
curl,python3(used only for local JSON formatting, optional). Ports 8080, 50000 and 3000 on this machine are free. - If you have completed the Docker course ’s myapp is better; if you do not have it, that is fine, and the full source code is given below (Flask + gunicorn + Redis counter, port 5000,
/healthz).
Directory structure (at the end of this lesson)
~/jenkinslab/
├── compose.yaml # jenkins, agent1, gitea: three services
├── .env # DOCKER_GID, AGENT1_SECRET (permissions 600, do not commit)
├── agent/Dockerfile # adds python3 and docker CLI on top of the official inbound-agent
├── .secrets/ # gitea-token, jenkins-token (permissions 700, do not commit)
└── myapp/ # pushed to the lab/myapp repo in Gitea
├── app.py requirements.txt requirements-dev.txt pytest.ini
├── tests/test_app.py
├── Dockerfile .dockerignore
└── Jenkinsfile # first version written in Module 5, full version in Module 7
Step 1: create directories and the agent image
The official jenkins/inbound-agent image only has Java and remoting (agent.jar), with no Python or Docker CLI. We add two things on top of it: the python3, and the docker CLI (copied from the official docker:29-cli image: static binary and buildx plugin).
mkdir -p ~/jenkinslab/{agent,myapp/tests,.secrets} && cd ~/jenkinslab
chmod 700 .secrets
cat > agent/Dockerfile <<'EOF'
# agent1: official inbound agent (JDK 21) + python3 + docker CLI
FROM jenkins/inbound-agent:3395.v6e5377b_0fb_3c-5-jdk21
USER root
RUN apt-get update \
&& apt-get install -y --no-install-recommends python3 python3-venv python3-pip git curl \
&& rm -rf /var/lib/apt/lists/*
# Only copy the client: the daemon is still dockerd on the host (accessed through the mounted docker.sock)
COPY --from=docker:29-cli /usr/local/bin/docker /usr/local/bin/docker
COPY --from=docker:29-cli /usr/local/libexec/docker/cli-plugins/docker-buildx /usr/local/libexec/docker/cli-plugins/docker-buildx
USER jenkins
EOF
Step 2: compose.yaml
cat > compose.yaml <<'EOF'
name: jenkinslab
services:
jenkins: # controller: schedules only, does not build
image: jenkins/jenkins:2.580.2-jdk21
container_name: jenkins
restart: unless-stopped
ports:
- "127.0.0.1:8080:8080" # Web UI / REST / CLI (bound to localhost only)
- "127.0.0.1:50000:50000" # inbound agent TCP port (only needed for agents outside compose)
environment:
JAVA_OPTS: "-Xms512m -Xmx1g"
volumes:
- jenkins_home:/var/jenkins_home # all configuration, jobs, build records, plugins, secrets
networks: [ci]
agent1: # permanent inbound agent, labels linux docker
build: ./agent
image: jenkinslab/agent1:jdk21
container_name: agent1
restart: unless-stopped
init: true
depends_on: [jenkins]
# Consistent with the official README: -url <controller> -workDir=<directory> <secret> <agent name>
command: ["-url", "http://jenkins:8080", "-workDir=/home/jenkins/agent", "${AGENT1_SECRET:-not-set}", "agent1"]
group_add:
- "${DOCKER_GID:-999}" # lets the jenkins user access docker.sock
volumes:
- agent1_work:/home/jenkins/agent # workspace and remoting cache
- /var/run/docker.sock:/var/run/docker.sock # ⚠ equivalent to host root privileges, lab use only
networks: [ci]
gitea: # local Git server: user lab, repo lab/myapp
image: gitea/gitea:28.4
container_name: gitea
restart: unless-stopped
environment:
USER_UID: "1000"
USER_GID: "1000"
GITEA__database__DB_TYPE: sqlite3
GITEA__server__ROOT_URL: http://localhost:3000/
GITEA__server__DISABLE_SSH: "true"
GITEA__security__INSTALL_LOCK: "true" # skip the web install page
GITEA__service__DISABLE_REGISTRATION: "true"
GITEA__webhook__ALLOWED_HOST_LIST: "private" # the Lesson 2 webhook must be sent to jenkins (private address)
ports:
- "127.0.0.1:3000:3000"
volumes:
- gitea_data:/data
networks: [ci]
volumes:
jenkins_home:
agent1_work:
gitea_data:
networks:
ci:
EOF
# .env: read automatically by compose. DOCKER_GID takes the group of docker.sock as seen inside the container; applies to both Linux and Docker Desktop
echo "DOCKER_GID=$(docker run --rm -v /var/run/docker.sock:/s alpine:3.22 stat -c %g /s)" > .env
echo "AGENT1_SECRET=" >> .env
chmod 600 .env
docker compose config --quiet && echo "compose.yaml OK"
compose.yaml OK
/var/run/docker.sock gives anyone who can run sh docker commands in agent1 the ability to docker run -v /:/host --privileged … obtain host root. We do this so that Lesson 1 can focus on Jenkins itself: the lab has only you as a user, ports are bound only to 127.0.0.1 localhost, and do not run untrusted code. Alternatives for production: ① a dedicated build VM as the agent (the isolation boundary is the VM); ② rootless Docker or docker:dind a sidecar (the approach used in the official Docker install guide, but it requires --privileged); ③ build tools that do not need a daemon (BuildKit rootless, Kaniko-style tools); ④ the ephemeral Kubernetes Pod agents from Lesson 5. Whichever option you choose,do not mount docker.sock on the controller, and do not build on the controller.Step 3: start jenkins and gitea
agent1 needs a secret, which only exists after you create the node in Jenkins (Module 1), so first start only the other two services, and build the agent image in the meantime:
docker compose build agent1 docker compose up -d jenkins gitea docker compose ps # wait for Jenkins to finish its first-time initialization (about 30–60 seconds) until docker compose logs jenkins 2>&1 | grep -q "Jenkins is fully up and running"; do sleep 3; done docker compose exec jenkins cat /var/jenkins_home/secrets/initialAdminPassword
NAME IMAGE SERVICE STATUS PORTS gitea gitea/gitea:28.4 gitea Up 20 seconds 127.0.0.1:3000->3000/tcp, 22/tcp jenkins jenkins/jenkins:2.580.2-jdk21 jenkins Up 20 seconds 127.0.0.1:8080->8080/tcp, 127.0.0.1:50000->50000/tcp 3f1c9a4e0b7d4e2c9a6b1f0d8e7c5a21
Open http://localhost:8080, and paste the 32-character initial password shown above. The setup wizard pages that follow are explained page by page in Module 2; if you want to finish setting up the environment first, follow the shortest path below:
- Customize Jenkins → Install suggested plugins (recommended plugins: 19, about 90 including dependencies; wait 2–5 minutes).
- Create First Admin User: Username
admin, set a strong password, and for email enteradmin@example.com. - Instance Configuration: keep the Jenkins URL as
http://localhost:8080/→ Save and Finish → Start using Jenkins.
Step 4: create user lab, an access token and a private repo in Gitea
cd ~/jenkinslab
read -rsp "Set the password for Gitea user lab: " GITEA_PASS; echo
# 1) create the admin user lab with the Gitea admin command (must run as the git user inside the container)
docker compose exec -u git gitea gitea admin user create \
--username lab --password "$GITEA_PASS" --email lab@example.com \
--admin --must-change-password=false
# 2) generate a repo-only access token for Jenkins (read/write repo: Lesson 2 needs it to write commit statuses back)
# -T: do not allocate a TTY, to avoid a trailing \r polluting the token file
docker compose exec -T -u git gitea gitea admin user generate-access-token \
--username lab --token-name jenkins-myapp --scopes write:repository \
| awk '{print $NF}' > .secrets/gitea-token
chmod 600 .secrets/gitea-token
GITEA_TOKEN=$(cat .secrets/gitea-token)
# 3) create the private repo lab/myapp via the API (default branch main)
curl -s -u "lab:$GITEA_PASS" -H "Content-Type: application/json" \
-X POST http://localhost:3000/api/v1/user/repos \
-d '{"name":"myapp","private":true,"default_branch":"main","description":"Jenkins 8h course sample app"}' \
| python3 -c 'import sys,json; d=json.load(sys.stdin); print(d["full_name"], d["private"], d["clone_url"])'
New user 'lab' has been successfully created! lab/myapp True http://localhost:3000/lab/myapp.git
http://localhost:3000/lab/myapp.git (ROOT_URL, for your browser and host machine). Jenkins and agent1 are on the compose network, for them localhost means the container itself, so you must use the service name http://gitea:3000/lab/myapp.git. This is the most common cause of clone failures in this lesson (see Module 8).Step 5: myapp source, tests and Dockerfile
cd ~/jenkinslab/myapp
cat > app.py <<'EOF'
import os
import socket
import redis
from flask import Flask
app = Flask(__name__)
r = redis.Redis(host=os.getenv("REDIS_HOST", "redis"), port=6379, socket_connect_timeout=1)
@app.get("/")
def index():
try:
hits = r.incr("hits")
except redis.exceptions.RedisError:
hits = "N/A (redis not connected)"
return f"Hello from {socket.gethostname()}, hits={hits}\n"
@app.get("/healthz")
def healthz():
return {"status": "ok"}
EOF
cat > requirements.txt <<'EOF'
flask==3.1.*
redis==5.*
gunicorn==23.*
EOF
cat > requirements-dev.txt <<'EOF'
-r requirements.txt
pytest==9.*
EOF
cat > pytest.ini <<'EOF'
[pytest]
pythonpath = .
testpaths = tests
EOF
cat > tests/test_app.py <<'EOF'
import redis
import app as appmod
def test_healthz():
resp = appmod.app.test_client().get("/healthz")
assert resp.status_code == 200
assert resp.get_json() == {"status": "ok"}
def test_index_without_redis(monkeypatch):
class Down:
def incr(self, key):
raise redis.exceptions.ConnectionError("redis down")
monkeypatch.setattr(appmod, "r", Down())
resp = appmod.app.test_client().get("/")
assert resp.status_code == 200
assert b"N/A" in resp.data
EOF
cat > Dockerfile <<'EOF'
# syntax=docker/dockerfile:1
FROM python:3.13-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py .
RUN useradd -m appuser
USER appuser
EXPOSE 5000
HEALTHCHECK CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:5000/healthz')" || exit 1
CMD ["gunicorn", "-b", "0.0.0.0:5000", "app:app"]
EOF
cat > .dockerignore <<'EOF'
.git
.venv
__pycache__
.pytest_cache
reports
tests
Jenkinsfile
EOF
cat > .gitignore <<'EOF'
.venv/
__pycache__/
.pytest_cache/
reports/
EOF
Compared with the myapp from the Docker course, only three things are added: /healthz returns JSON,tests/ the two pytest cases under (the second case uses monkeypatch to simulate Redis being unavailable, so CI does not need Redis),pytest.ini in the pythonpath = . (otherwise import app will report ModuleNotFoundError).
Step 6: push to Gitea
cd ~/jenkinslab/myapp git init -b main git add . && git commit -m "myapp: Flask app, tests and Dockerfile" git remote add origin http://localhost:3000/lab/myapp.git # the token is only placed in the HTTP header of this one command, and is not written to .git/config or the remote URL AUTH=$(printf 'lab:%s' "$(cat ../.secrets/gitea-token)" | base64 | tr -d '\n') git -c http.extraHeader="Authorization: Basic $AUTH" push -u origin main git ls-remote origin
To http://localhost:3000/lab/myapp.git * [new branch] main -> main branch 'main' set up to track 'origin/main'. 9b2f6c1d0e4a8b7c3f5d2e1a0c9b8d7e6f5a4b3c HEAD 9b2f6c1d0e4a8b7c3f5d2e1a0c9b8d7e6f5a4b3c refs/heads/main
Future pushes can keep using the same git -c http.extraHeader=… push, or follow Git course to configure a credential helper.
Environment self-check checklist
docker compose stop; full cleanup (this deletes all Jenkins configuration, build records and Gitea repos): docker compose down -v && docker image rm jenkinslab/agent1:jdk21 myapp:1.0. Lesson 2 continues using this environment, so after finishing this lesson do not run down -v.Module 1 · Jenkins architecture: controller, agent, executor and queue
- Explain controller, node, agent, executor, label, queue, workspace, JENKINS_HOME the eight concepts and how they relate.
- Describe the full lifecycle of a build: trigger → enter queue (waiting / blocked / buildable) → label matching → assign executor → workspace → step execution → log and artifact return → result.
- Understand why the official guidance recommends not building on the built-in node, and the significance of agent → controller access control (always enabled since 2.326).
- Create the permanent node agent1 in the lab environment (label
linux docker) and connect it via inbound.
What: what Jenkins is
Jenkins is an open-source automation server (MIT license, written in Java, community hosted by the CD Foundation), distributed as a WAR file and able to run on Docker, Kubernetes, Linux/Windows/macOS. By itself it only provides scheduling, the Job model, the Web UI, REST/CLI and a security framework; nearly all of the “doing things” features — Git pulls, Pipeline, credentials, Docker, Kubernetes — come from plugins (Module 3).
| Concept | What it is | In the lab environment |
|---|---|---|
| controller (formerly called master) | The Jenkins main process: stores configuration, provides the UI/API, maintains the queue, schedules builds, runs the Groovy logic of Pipelines, and stores logs and artifacts | Container jenkins |
| node | the generic name for machines that can execute builds, including the built-in node and each agent | Built-In Node, agent1 |
| agent | via remoting (agent.jar), a remote node that connects to the controller and actually runs sh,git,docker build | Container agent1 |
| executor | a “build slot” on a node, i.e. one execution thread. A node with N executors can run N builds at the same time (or Pipeline node blocks) | agent1: 2; built-in node: 0 |
| label | A label on a node; builds use label expressions (such as linux && docker) to declare what kind of node they need | agent1: linux docker |
| queue | The list of tasks waiting to run; each task passes in turn through waiting (quiet period) → blocked (being blocked) → buildable (waiting for a free executor) | /queue/api/json |
| workspace | The directory on a node assigned to a Job; code checkout and builds happen here, and it is kept between builds by default | /home/jenkins/agent/workspace/myapp |
| JENKINS_HOME | The controller’s data directory: config.xml, jobs/, builds/, plugins/, secrets/, credentials.xml, nodes/ | volume jenkins_home → /var/jenkins_home |
Why: why separate the controller and the agents
- Security: the official docs Controller Isolation state that any build running on the built-in node has the same access to the controller’s filesystem as the Jenkins process — build scripts can read
secrets/and all credentials. Therefore, the official guidance is to “strongly recommend against running any build on the built-in node.” - Stability: the controller is a single point of failure; when builds compete for its CPU, memory and disk I/O, the UI lags, the queue stalls, and even OOM can interrupt all builds. The official node documentation recommends setting the controller’s executor count to 0, so builds run only on agents.
- Heterogeneity and scaling: Linux, Windows, macOS, GPU and ARM each have their own agents, distinguished by labels; when more capacity is needed, add agents rather than scaling up the controller.
How: how agents connect to the controller
| Method | Who initiates | Network requirements | Best for |
|---|---|---|---|
| Inbound TCP (inbound, used in this lesson) | the agent connects to the controller | first accesses HTTP(S) to get the port and identity, then connects to the TCP inbound port (default 50000 in the official image) | agents behind NAT/firewalls, containers, ephemeral Pods |
| Inbound WebSocket | the agent connects to the controller | only needs the controller’s HTTP(S) port, not 50000 | a reverse proxy/load balancer in front of the controller, only 443 open |
| SSH (SSH Build Agents plugin) | controller connects to agent | the controller can SSH to the agent, and the agent has Java | fixed Linux build machines |
| Cloud / dynamic (Kubernetes, EC2 Fleet, Azure VM and similar plugins) | plugins create agents on demand and destroy them afterwards | depends on the cloud | elastic capacity (Lessons 4 and 5) |
Once the connection is established, the controller and agent share a bidirectional remoting channel: the controller sends requests such as “run this process, read this file” to the agent, and the agent streams output back to the controller. Agent → Controller access control Prevents agents from sending malicious commands back to the controller; always enabled since 2.326, and the official guidance strongly recommends not bypassing it.
When: when more agents / more executors are needed
- If the queue often shows “Waiting for next available executor” → insufficient capacity: add agents, or, when CPU/memory has headroom, raise a single agent’s executors from 1 to 2–4.
- If the queue shows “There are no nodes with the label …” → the label is wrong or that type of agent is missing; adding executors will not help.
- A memory-hungry build (such as a Docker build or Java compilation) → 1 executor per agent is more stable; lightweight script-type tasks can run several.
Comparison with GitHub Actions and Azure Pipelines
| Jenkins | GitHub Actions | Azure Pipelines |
|---|---|---|
| controller (self-hosted) | GitHub-hosted service | Azure DevOps-hosted service |
| agent + executor | runner (each runner runs one job at a time) | agent (each agent runs one job at a time) + parallel job licenses |
label expression linux && docker | runs-on: [self-hosted, linux] | pool + demands |
| Queue (in controller memory) | jobs queue waiting for a runner | jobs queue waiting for an agent and parallel job capacity |
| Jenkinsfile (Groovy DSL) | .github/workflows/*.yml | azure-pipelines.yml |
See GitHub course and Azure DevOps course. The biggest difference: you run the Jenkins controller yourself (upgrades, plugins, backups, security); it is flexible, but all of the responsibility is yours too.
agent / node blocks take up an executor on an agent. ③ “Renaming master is just a word change”—— 2.307 (LTS 2.319.1) renamed the master node to the built-in node, and at the same time changed its label from master to built-in; new installs take effect directly, while older instances upgraded to this version need the administrator to apply the migration manually from the prompt; Jobs that depend on the old label master need to be adjusted. ④ “The workspace is deleted once the build finishes”—— it is kept by default unless you use cleanWs() or the Workspace Cleanup plugin.Architecture diagram: lab environment ~/jenkinslab
Workflow diagram: components a build passes through
Core animation: the lifecycle of a build
Using a Pipeline Job myapp (in the Jenkinsfile agent { label 'linux && docker' }) as an example. Each step highlights the corresponding component, and the right side shows the real state of the queue item (corresponding to /queue/api/json fields), and the terminal below shows the real output you would see in the console log. Choose different scenarios to see at which step the build gets stuck and what it reports.
(not yet triggered)
hudson.model.Queue represents the task as WaitingItem (during the quiet period) → BlockedItem (blocked by other builds or resources) → BuildableItem (can run, waiting for an executor) → leaves the queue and becomes LeftItem (with executable set to the build number). In a Pipeline, the agent block submits another placeholder task “part of myapp #N”, which likewise goes through label matching and executor assignment; this is why “Still waiting to schedule task” appears in Pipeline logs.Command table
| Command / interface | Purpose | Key parameters |
|---|---|---|
GET /computer/api/json | Lists all nodes, online status, executor count and labels | tree=computer[displayName,offline,numExecutors,assignedLabels[name]] |
GET /queue/api/json | Shows the status and reason of each item in the queue (why) | tree=items[id,task[name],why,blocked,buildable,stuck,inQueueSince] |
GET /computer/agent1/jenkins-agent.jnlp | Gets the connection parameters of an inbound agent (including the secret); requires the node’s Connect permission | authenticates with an API token |
docker compose logs agent1 | View remoting handshake and disconnect reasons | -f,--since 10m |
CLI list-computers/offline-node/online-node | node management (Jenkins CLI; see the jcli function in Module 2) | -m "reason" |
cd ~/jenkinslab JT=$(cat .secrets/jenkins-token) # admin API token generated in the Module 2 lab curl -s -u "admin:$JT" "http://localhost:8080/computer/api/json?tree=computer[displayName,offline,numExecutors,assignedLabels[name]]" | python3 -m json.tool
{
"_class": "hudson.model.ComputerSet",
"computer": [
{ "displayName": "Built-In Node", "numExecutors": 0, "offline": false,
"assignedLabels": [ { "name": "built-in" } ] },
{ "displayName": "agent1", "numExecutors": 2, "offline": false,
"assignedLabels": [ { "name": "agent1" }, { "name": "docker" }, { "name": "linux" } ] }
]
}
How to verify: A node’s own name is also a label (agent1), so agent { label 'agent1' } you can pin a build to a specific node (not recommended, as it loses scheduling flexibility). Common errors: 401 returned → wrong token or username; 403 returned → that user does not have Overall/Read. Production use: A monitoring script periodically checks offline: true nodes and raises alerts.
# Watch the queue: run this right after triggering a build curl -s -u "admin:$JT" "http://localhost:8080/queue/api/json?tree=items[id,task[name],why,blocked,buildable,stuck]" | python3 -m json.tool
{
"items": [
{ "id": 17, "task": { "name": "part of myapp #4" },
"why": "There are no nodes with the label ‘windows’",
"blocked": false, "buildable": true, "stuck": false }
]
}
stuck: true means the item has been runnable for a long time but never gets an executor (typically no online node matches its label), making it a good alerting metric.
Goal: Set the built-in node to 0 executors, create the permanent node agent1, and connect it via inbound. Environment: Module 0 has started jenkins and gitea, and the setup wizard has been completed. Cost: None.
0 → Save. From then on, no build will run on the controller.agent1, type Permanent Agent → Create, then fill in:
| Field | Value | Notes |
|---|---|---|
| Number of executors | 2 | Runs at most 2 builds at the same time |
| Remote root directory | /home/jenkins/agent | Matches the -workDir path and volume in compose |
| Labels | linux docker | Space-separated multiple labels |
| Usage | Only build jobs with label expressions matching this node | Jobs without a label will not run here |
| Launch method | Launch agent by connecting it to the controller | Inbound |
| Availability | Keep this agent online as much as possible | Default |
http://localhost:8080/computer/agent1/, which shows the connection command; the 64-character hexadecimal string in it is the secret.
cd ~/jenkinslab
read -rsp "Paste agent1's secret: " S; echo
sed -i "s/^AGENT1_SECRET=.*/AGENT1_SECRET=$S/" .env # macOS: sed -i '' …
# or via the API (requires the Module 2 API token): the secret is the first argument in the JNLP file
curl -s -u "admin:$(cat .secrets/jenkins-token)" http://localhost:8080/computer/agent1/jenkins-agent.jnlp \
| sed -n 's|.*<argument>\([0-9a-f]\{64\}\)</argument>.*|\1|p'docker compose up -d agent1 docker compose logs agent1 | tail -n 15
agent1 | INFO: Locating server among [http://jenkins:8080/] agent1 | INFO: Agent discovery successful agent1 | Agent address: jenkins agent1 | Agent port: 50000 agent1 | INFO: Handshaking agent1 | INFO: Connecting to jenkins:50000 agent1 | INFO: Trying protocol: JNLP4-connect agent1 | INFO: Remote identity confirmed: 4a:91:...:c2 agent1 | INFO: Connected
docker compose exec agent1 id
docker compose exec agent1 docker version --format '{{.Client.Version}} / {{.Server.Version}}'
docker compose exec agent1 python3 --version
uid=1000(jenkins) gid=1000(jenkins) groups=1000(jenkins),988 29.10.0 / 29.10.0 Python 3.13.5
The 988 in groups is the DOCKER_GID in .env (it differs per machine). The Python version depends on the inbound-agent base image (Debian).
Case 1: controller OOM takes down the whole platform
Problem: Early on, the team built directly on the controller (built-in node with 4 executors); a large parallel Maven build exhausted memory, the Jenkins process was killed by the OOM Killer, all of the 30+ running builds were interrupted, and the UI was down for 20 minutes. Fix: Set the built-in node executors to 0; add 3 Linux agents with 2 executors each; size the controller’s JVM heap per the official hardware recommendations, and monitor it separately. Configuration: Nodes → Built-In Node → executors 0; all Jobs explicitly write agent { label 'linux' }. Limitation: Older Freestyle Jobs have no label restriction; you need to batch-add “Restrict where this project can be run”.
Case 2: agents behind a firewall connect using WebSocket
Problem: The controller is deployed behind a load balancer that only opens 443, and the security team is unwilling to open port 50000. Fix: Switch the agent to WebSocket mode (using the -webSocket parameter), so only HTTPS is used. Limitation: The reverse proxy must correctly support WebSocket upgrades and a long idle timeout, otherwise the connection will drop periodically.
Case 3: use labels to distinguish capabilities rather than machines
Problem: A Job hard-codes label 'build-server-03', so when that machine is under maintenance all builds queue up. Fix: Label by capability (linux,docker,jdk21,arm64), and Jobs write an expression linux && docker, so machines of the same kind back each other up. Limitation: Labels need a naming convention and an inventory, otherwise you will end up with Docker and docker such case mismatches (labels are case-sensitive).
Common errors and fixes
SEVERE: http://jenkins:8080/ provided port:50000 is not reachable on host jenkins
Cause: The agent can reach HTTP but cannot connect to the inbound TCP port: the port is disabled (Security → Agents → TCP port for inbound agents set to Disable), the port number differs, or a firewall blocks it.
curl -sI http://localhost:8080/tcpSlaveAgentListener/ | grep -i x-jenkins-jnlp-port docker compose exec agent1 bash -c 'timeout 3 bash -c "</dev/tcp/jenkins/50000" && echo open'
Fix: Enable fixed port 50000 (already enabled by default in the official image); or switch to WebSocket (adding -webSocket to the compose command).
SEVERE: The server rejected the connection: None of the protocols were accepted / Unauthorized access
Cause: The secret is wrong (copied incorrectly, or changed after the node was deleted and recreated), or the node name does not match the secret.
grep AGENT1_SECRET ~/jenkinslab/.env | cut -c1-25 docker compose logs agent1 --since 5m | grep -iE "secret|rejected|unauthor"
Fix: Get the secret again from the node page, update .env, then docker compose up -d agent1 (compose will recreate the container because the parameters changed).
The build keeps showing “Waiting for next available executor on ‘Built-In Node’”
Cause: The Job has no label (or has written built-in), while the built-in node has 0 executors; agent1 only runs Jobs whose labels match.
Fix: Write in the Jenkinsfile agent { label 'linux && docker' }; for Freestyle Jobs, tick “Restrict where this project can be run” and enter the label.
agent1 is offline: Agent went offline during the build / java.nio.channels.ClosedChannelException
Cause: The agent container restarts or is killed by OOM, the network drops, or the controller restarts.
docker compose ps agent1
docker inspect agent1 --format '{{.State.OOMKilled}} {{.RestartCount}}'
docker compose logs agent1 --since 15m | tail -n 30
Fix: Give Docker enough memory; the agent’s restart: unless-stopped will reconnect automatically; an interrupted Pipeline must be rerun (Lesson 2 covers how Pipelines recover after a controller restart).
1. Using a single curl command, list the names of all offline nodes.
curl -s -u "admin:$JT" "http://localhost:8080/computer/api/json?tree=computer[displayName,offline]" \ | python3 -c 'import sys,json; print([c["displayName"] for c in json.load(sys.stdin)["computer"] if c["offline"]])'
2. Check why each item in the queue is still waiting.
curl -s -u "admin:$JT" "http://localhost:8080/queue/api/json?tree=items[task[name],why]" | python3 -m json.tool
A Jenkins instance has only a controller (built-in node with 2 executors); the team wants to run Docker builds on it and also wants to mount docker.sock into the controller container. Assess the risks and propose a redesign.
Risk: when builds run on the built-in node, they can read JENKINS_HOME/secrets the controller’s files and all credentials; mounting docker.sock on top of that gives anyone who can edit the Jenkinsfile host root. Plan: set the built-in node executors to 0; add separate agents (dedicated VMs or containers) and provide Docker on the agents (ideally a dedicated build VM or a rootless / ephemeral Pod approach); have Jobs use labels linux && docker to target; the controller exposes only the necessary ports, and back up JENKINS_HOME.
Verified teaching videos
Official docs
Video storyboard script (about 90 seconds)
This courseware cannot generate video/MP3 directly; the storyboard and narration script are provided, to be passed to a video tool for generation.
Visual: a large box “controller” containing the UI, queue and JENKINS_HOME; beside it, two small boxes “agent1” and “agent2”.
Narration: Jenkins is split into two parts: the controller schedules and stores everything, and agents actually run the builds.
Visual: click Build Now; a card enters the queue and passes through two gates, “quiet period” and “label match”.
Narration: the build first enters the queue, waits for the quiet period to end, then looks for a node with a matching label and a free executor.
Visual: the card lands in an executor slot on agent1, the workspace directory expands, the terminal scrolls sh output, and the output flows back to the controller along the arrow.
Narration: the steps run in the agent’s workspace, and logs stream back to the controller in real time to be saved.
Visual: the built-in node’s executor slot is marked with a red cross and “0”.
Narration: with the built-in node’s executors set to zero, build scripts cannot touch the controller’s keys and configuration.
Module 2 · Installation and setup: LTS, Docker image and setup wizard
- Distinguish the LTS and weekly release lines, and read official Docker image tags (
2.580.2-jdk21,lts-jdk21,latest,slim,alpine,rhel-ubi9). - Know the Java support policy: Java 21 and 25 are supported; from 2.555.1 LTS onward, Java 21+ is required.
- Understand what Jenkins does on first startup: generates
initialAdminPassword, enters the installation state machine, installs suggested plugins, creates the admin user, and sets the Jenkins URL. - Recognize the JENKINS_HOME directory structure and know how to back up and upgrade it; generate an API token and configure the Jenkins CLI.
What: two release lines
| LTS (Long-Term Support) | Weekly | |
|---|---|---|
| Cadence | Roughly every 12 weeks, one weekly is picked as the new baseline (e.g. 2.580), followed by .1, .2 and .3 patch releases | One release per week (2.588 → 2.589 → 2.590) |
| Current (as of 2026-11-16) | 2.580.2 (2026-10-28); 2.580.1 on 2026-09-30 | 2.590 (2026-11-09) |
| Content | Only backports verified fixes and security patches | New features and fixes; changes fastest |
| Docker tags | lts,lts-jdk21,2.580.2-jdk21 | latest,jdk21,2.590-jdk21 |
| Best for | Production (used throughout this course) | Test instances that want to try new features early |
Java support (official Java support policy page)
| Java | First LTS | First weekly | Planned end of support |
|---|---|---|---|
| Java 25 | 2.541.1 (2026-01) | 2.534 (2025-10) | 2029-09 |
| Java 21 | 2.479.1 (2024-10) | 2.463 (2024-06) | 2027-09 |
| Java 17 (discontinued) | the last LTS is 2.541.3 (2026-03) and the last weekly is 2.544; from 2.555.1 onward Java 21 or later is required, and the Java 17 controller image has been removed | ||
Used in this lesson -jdk21 image; -jdk25 an equivalent image is also available. Note that Java 21 is planned to reach end of support in 2027-09; production environments should plan the switch to Java 25 before then (agents must be upgraded too, and it is recommended that the controller and agents use the same Java version).
How to choose an official image tag
| Tag | Meaning | Recommendation |
|---|---|---|
2.580.2-jdk21 | Pinned LTS version + JDK 21 (Debian base) | Preferred for production: repeatable and rollback-able |
2.580.2-lts-jdk21 | Same as above, alias with the lts label | Same as above |
lts-jdk21 / lts | Floating tag, always pointing to the latest LTS | Good for learning; in production it would be upgraded without you knowing |
latest | Latest weekly | Do not use in production |
-slim / -alpine / -rhel-ubi9 | Smaller Debian / Alpine / Red Hat UBI 9 bases | Choose according to enterprise base image requirements |
-windowsservercore-ltsc2022/2025 | Windows containers | Windows 2019 images are no longer provided from 2.568.1 onward |
How: what happens on first startup
- The container entrypoint script copies
/usr/share/jenkins/ref/the contents of (for example, plugins preinstalled in the image) into the emptyJENKINS_HOME, then startsjava -jar jenkins.war(embedded Jetty, port 8080). - Jenkins finds
JENKINS_HOMEis brand new → install state is NEW → security is enabled and a random initial admin password is generated and written tosecrets/initialAdminPasswordand printed to the log. - When accessed from a browser, it enters the setup wizard: Unlock Jenkins → choose plugins (suggested plugins or a custom selection) → download and install plugins and dependencies from the Update Center → create the first admin → set the Jenkins URL → run.
- Once complete, it writes
jenkins.install.InstallUtil.lastExecVersion, the initial password file is deleted,initialAdminand the setup account becomes invalid. On later startups Jenkins sees these files and does not enter the wizard again.
JENKINS_HOME directory structure (excerpt)
| Path | Contents | Back up? |
|---|---|---|
config.xml | Global configuration: security realm, authorization strategy, executor count, views, etc. | Required |
jobs/<name>/config.xml | Configuration of each Job | Required |
jobs/<name>/builds/<N>/ | build.xml, log, archive/, test results | As needed (may be very large) |
nodes/<name>/config.xml | Node definitions (agent1’s labels, executor count) | Required |
credentials.xml | Global credentials (encrypted storage) | Required, and secrets/ must be backed up at the same time |
secrets/ | master.key,hudson.util.Secret and other encryption keys | Required, stored separately and encrypted |
plugins/ | Installed .jpi and extracted directories | can be rebuilt from plugins.txt |
users/ | Local users, API tokens (hashed) | Required |
workspace/,caches/ | built-in node workspaces and caches | Not needed |
When: how to choose an installation method
| Method | Best for | Notes |
|---|---|---|
| Docker / Compose (this lesson) | Learning, single-node production, easy to upgrade and roll back | JENKINS_HOME must be on a volume; the in-container user is UID 1000 |
| Kubernetes Helm chart | Platform teams, combined with JCasC | Lesson 5 |
| Linux packages (apt/yum, systemd) | Traditional VMs | Java must be installed and upgraded separately |
| Windows MSI | Must run the controller on Windows | Windows 2019 users can only use MSI or a self-built image |
| Run the WAR directly | Temporary testing | Not recommended for production |
latest is the most stable”——latest is a weekly. ② “Deleting and rebuilding the container loses the configuration”—— as long as the jenkins_home volume still exists, all configuration is kept; conversely,docker compose down -v will also delete the volume. ③ “If the initial password is lost, you have to reinstall”—— before the wizard is complete, you can find it in secrets/initialAdminPassword or in the container logs. ④ “Backing up only credentials.xml is enough to restore credentials”—— without secrets/ the keys in it, the credentials cannot be decrypted.Sequence of first startup and setup wizard
Data flow for upgrade and rollback
Animation: first startup and installation state machine
Jenkins uses jenkins.install.InstallState to record installation progress. Choose “a fresh volume” or “an existing volume” and observe whether the wizard appears and which files each step writes.
Command table
| Command | Purpose | Key parameters |
|---|---|---|
docker compose exec jenkins cat /var/jenkins_home/secrets/initialAdminPassword | Get the initial password | The file is deleted after the wizard completes |
docker compose logs jenkins | startup logs, plugin loading errors | -f,--since |
curl -sI http://localhost:8080/login | From the X-Jenkins response header, read the version | — |
java -jar jenkins-cli.jar -s URL … | Jenkins CLI (HTTP mode) | -auth or environment variable JENKINS_USER_ID / JENKINS_API_TOKEN |
jcli version / who-am-i / help | Verify CLI and identity | — |
jcli safe-restart | Wait for running builds to finish before restarting | — |
Read the version and Jenkins CLI configuration
curl -sI http://localhost:8080/login | grep -i '^x-jenkins:'
# download the CLI matching the controller version (saved to the volume, so it survives container rebuilds)
cd ~/jenkinslab
docker compose exec jenkins curl -sSo /var/jenkins_home/jenkins-cli.jar http://localhost:8080/jnlpJars/jenkins-cli.jar
# define jcli: run the CLI in the jenkins container, passing the token via an environment variable (so it does not appear in CLI arguments)
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/ "$@"
}
jcli version
jcli who-am-i
X-Jenkins: 2.580.2 2.580.2 Authenticated as: admin Authorities: authenticated
How to verify:who-am-i Shows Authenticated as: admin; if it shows anonymous means the token was not passed in. Common errors:ERROR: You must authenticate to access this Jenkins.—— the token file is empty or the token has been revoked. Production use: Scripted export of Job configuration, batch starting and stopping of nodes, safe restarts. You can add the jcli function to ~/.bashrc, which later modules will all use.
Backup and upgrade
cd ~/jenkinslab # back up (volume name = project name_volume name). In production, first put Jenkins into quiet mode: jcli quiet-down docker run --rm -v jenkinslab_jenkins_home:/src:ro -v "$PWD":/backup alpine:3.22 \ tar czf /backup/jenkins_home-$(date +%F).tgz -C /src --exclude=./workspace --exclude=./caches . ls -lh jenkins_home-*.tgz # upgrade (example: after the next LTS patch is released): change the tag → pull → rebuild the container; the volume stays unchanged # sed -i 's|jenkins/jenkins:2.580.2-jdk21|jenkins/jenkins:<new version>-jdk21|' compose.yaml docker compose pull jenkins && docker compose up -d jenkins
-rw-r--r-- 1 user user 92M Nov 16 10:20 jenkins_home-2026-11-16.tgz
secrets/ and credentials.xml, and with it anyone can decrypt all credentials. Store it encrypted (for example age / gpg), and do not put it in a shared directory.Goal: Confirm the setup wizard results, generate an API token for admin, configure jcli, and back up JENKINS_HOME once. Environment: Module 0 has completed the setup wizard. Cost: None.
| Wizard page | What it did | Where to change it later |
|---|---|---|
| Unlock Jenkins | Proves you can read the container filesystem | — |
| Customize Jenkins | Installs suggested plugins (Folders, Pipeline, Git, Credentials Binding, Timestamper, Workspace Cleanup, Pipeline Graph View, Matrix Authorization, SSH Build Agents, etc.) | Manage Jenkins → Plugins |
| Create First Admin User | Creates in Jenkins’ built-in user database admin | Manage Jenkins → Users |
| Instance Configuration | Jenkins URL (used for links in emails and status write-backs) | Manage Jenkins → System → Jenkins URL |
lab-cli → Generate → copy (shown only once).
cd ~/jenkinslab read -rsp "Paste the admin API token: " T; echo printf '%s' "$T" > .secrets/jenkins-token && chmod 600 .secrets/jenkins-token curl -s -u "admin:$(cat .secrets/jenkins-token)" http://localhost:8080/whoAmI/api/json | python3 -m json.tool | head -n 6
{
"_class": "hudson.security.WhoAmI",
"anonymous": false,
"authenticated": true,
"authorities": [
"authenticated"
Calling REST/CLI with an API token does not need a CSRF crumb; only sessions logged in with a password need one. Tokens can be revoked at any time on the same page.
jcli() function definition from the “Commands” tab, then:
jcli version jcli list-plugins | wc -l
2.580.2 92
docker compose exec jenkins ls /var/jenkins_home docker compose exec jenkins cat /var/jenkins_home/jenkins.install.InstallUtil.lastExecVersion; echo docker compose exec jenkins ls /var/jenkins_home/secrets
config.xml jenkins-cli.jar jenkins.install.InstallUtil.lastExecVersion jobs nodes plugins secrets updates userContent users ... 2.580.2 hudson.util.Secret jenkins.model.Jenkins.crumbSalt master.key org.jenkinsci.main.modules.instance_identity.InstanceIdentity.KEY ...
Note secrets/ under it there is no longer initialAdminPassword: it is deleted once the wizard completes.
jenkins_home-date.tgz, then move it to an encrypted location or delete it (for lab use).Case 1: “weekend automatic upgrade” caused by a floating tag
Problem: The production compose uses jenkins/jenkins:lts, and on a weekend node restart it pulled a new LTS baseline; some older plugins were incompatible with the new core, so on Monday all Pipelines errored. Fix: Change to a pinned tag 2.580.2-jdk21, and upgrades go through a change process: read the upgrade guide → verify on a staging instance → back up → upgrade. Limitation: A pinned tag means you must actively track security advisories (the 2026-10-28 advisory includes a core fix); otherwise you stay exposed to vulnerabilities for a long time.
Case 2: offline environment installation
Problem: The internal network cannot reach updates.jenkins.io, and the wizard gets stuck at plugin installation. Fix: On a networked machine, preinstall plugins into a custom image (Module 3’s plugins.txt + jenkins-plugin-cli), push the image to the internal registry; or set up an internal Update Center mirror. Limitation: From 2.580.1 onward, several plugins (such as bouncycastle API, Instance Identity, JavaMail API, etc.) are no longer bundled in the WAR; offline instances must put these plugins into plugins/, otherwise it may fail to start.
Case 3: forced upgrade when Java 17 reaches end of support
Problem: A team was still running 2.541.x on a Java 17 VM in 2026 and wanted to upgrade to an LTS after 2.555.1. Fix: First upgrade Java on the controller and all agents to 21 (or straight to 25), verify on 2.541.3, then upgrade Jenkins. Limitation: An unsupported Java version will prevent the controller from starting, and an old Java on an agent will also cause connection failures.
Common errors and fixes
touch: cannot touch '/var/jenkins_home/copy_reference_file.log': Permission denied
Cause: A host directory is bind-mounted to JENKINS_HOME, but the directory owner is not UID 1000 (the jenkins user inside the container).
docker compose run --rm --entrypoint id jenkins ls -ln /path/to/jenkins_home
Fix: Use a named volume (as this lesson does), or sudo chown -R 1000:1000 /path/to/jenkins_home.
An error occurred during installation: No such plugin: xxx / large-scale plugin installation failures in the wizard
Cause: The container cannot reach the Update Center (proxy, DNS, TLS interception).
docker compose exec jenkins curl -sI https://updates.jenkins.io/update-center.json | head -n 1 docker compose logs jenkins | grep -iE "updatecenter|SSLHandshake|UnknownHost" | tail
Fix: Configure a proxy (Manage Jenkins → Plugins → Advanced settings → HTTP Proxy); for enterprise TLS interception, import the root certificate into the JVM truststore; or in the wizard choose “Retry”, and failed plugins can be reinstalled on the Plugins page.
Running with Java 17 … which is older than the minimum required version (Java 21)
Cause: Starting Jenkins 2.555.1 or later on Java 17 (common with package installs or self-built images).
java -version docker compose exec jenkins java -version
Fix: Install Java 21 or 25; for the container approach, directly use the -jdk21 / -jdk25 tag.
After rebuilding the container, it asks for initialAdminPassword again / all configuration is lost
Cause: JENKINS_HOME is not mounted to a volume (data lives in the container’s writable layer and is deleted with it), or you ran docker compose down -v.
docker volume ls | grep jenkins_home
docker inspect jenkins --format '{{range .Mounts}}{{.Name}} -> {{.Destination}}{{"\n"}}{{end}}'
Fix: Make sure jenkins_home:/var/jenkins_home; to restore from backup, after creating a new volume, tar xzf extract the backup back into it.
1. Without logging in through the browser, confirm the version of the running Jenkins.
curl -sI http://localhost:8080/login | grep -i '^x-jenkins:' # or: jcli version
2. Back up JENKINS_HOME to the current directory (excluding workspaces).
docker run --rm -v jenkinslab_jenkins_home:/src:ro -v "$PWD":/backup alpine:3.22 \ tar czf /backup/jh.tgz -C /src --exclude=./workspace .
The team wants to “always use the latest version” and writes in compose jenkins/jenkins:latest, and says “there are backups anyway.” How would you assess this?
latest is a weekly that changes every week and is unsuitable for production; even with LTS you should pin to a specific version (e.g. 2.580.2-jdk21). “Having backups” does not mean you can roll back: data formats migrate after an upgrade, so rolling back requires restoring the backup taken before the upgrade, and build records from the interim are lost. Recommendations: pin the LTS tag → subscribe to security advisories and the LTS changelog → verify on staging → back up → upgrade → smoke build.
Verified teaching videos
official documentation
Video storyboard script (about 75 seconds)
This lesson cannot directly generate a video or MP3, so a storyboard and narration script are provided instead.
Visual: two timelines; the top one has a dot for each week (weekly), the bottom one a large dot every 12 weeks plus small patch dots (LTS).
Narration: production uses only LTS and pins to a specific version number.
Visual: the terminal runs docker compose up and the log shows a 32-character password; the browser shows the Unlock page.
Narration: a brand-new data volume triggers the setup wizard, and the initial password is written to the secrets directory and the log.
Visual: plugin installation progress bar, with ninety plugins turning green one by one.
Narration: 19 recommended plugins, about 90 including dependencies, all with versions chosen to be compatible with the current core version.
Visual: the volume icon is packed into a tgz, with a lock beside it.
Narration: back up before upgrading; the backup contains keys, so store it encrypted.
Module 3 · Plugin system: installation, dependencies and the Update Center
- Understand what plugins are (extension points +
.jpipackaging), dependency relationshipsrequiredCore, and how the Update Center picks versions compatible with your core version. - Know the recommended plugins and the key plugins used in this course, with their current versions; know how Blue Ocean, Pipeline Stage View and Pipeline Graph View relate.
- Be able to use the UI, the Jenkins CLI, and
plugins.txt+jenkins-plugin-clithree methods to install and pin plugin versions. - Be able to handle security advisories, deprecated plugins, and load failures caused by missing dependencies.
jcli. Importance:★★★★☆What: what a plugin is
A plugin is a .jpi (historically called .hpi) file, essentially a JAR with a manifest. It plugs into Jenkins through the core-defined extension points (extension point): new SCMs (Git), new build steps (sh,junit new credential types, new agent launch methods, new UI pages. Each plugin declares in its manifest:
- Dependencies: required and optional dependencies with minimum versions, for example the Gitea plugin depends on git ≥ 5.10.1, credentials, scm-api, branch-api, and so on.
- requiredCore: minimum core version, for example Gitea 286.v0740a_413c1eb_ requires 2.528.3, and Prometheus metrics 873.v054598e6e84d requires 2.555.3.
Plugin version numbers come in two styles: traditional 5.11.0 (Git plugin) and the automated-release style 1514.vb_01eb_014e7d4 (build number + Git commit hash, Credentials plugin); the latter has no semantic-versioning meaning and can only be compared by order.
Why: why dependencies and versions are the number-one operations problem
- One recommended install brings in about 90 plugins, and each may have its own release cadence and security advisories.
- Plugins have transitive dependencies: upgrading A may require upgrading B first, and B in turn requires a newer core.
- Plugins run inside the controller's JVM, so a vulnerable plugin is a vulnerability in the controller. Most Jenkins security advisories concern plugins (for example, the 2026-09-16 and 2026-06-24 advisories involved only plugins).
How: how the Update Center picks versions
Jenkins requests https://updates.jenkins.io/update-center.json?version=<core version>, and the server returns trimmed for this core version metadata: for each plugin it gives only the latest version compatible with that core, plus its dependencies, checksums, security warnings and deprecation information. Using the 2026-11-16 data as an example:
| Plugin | Latest version on plugins.jenkins.io | Core it requires | Version the Update Center gives for 2.580.2 |
|---|---|---|---|
| JUnit | 1463.v7508416a_349c (2026-11-15) | 2.589 (weekly) | 1458.1460.vd53b_087eeb_2c (requires 2.555.3) |
| Pipeline Graph View | 1134.v63b_71c6f549b_ (2026-11-16) | 2.589 | 1053.v9df19e6ceed2 (requires 2.555.3) |
| Git | 5.11.0 | 2.504.3 | 5.11.0 |
| Gitea | 286.v0740a_413c1eb_ | 2.528.3 | 286.v0740a_413c1eb_ |
This is why LTS users sometimes “cannot see the latest version” on the plugin page: the newest version needs a newer core, so the Update Center offers the highest compatible version you can use.
Key plugins used in this course (versions offered by the Update Center for 2.580.2, 2026-11-16)
| Plugin (ID) | Version | Purpose | When to use |
|---|---|---|---|
| Pipeline (workflow-aggregator) | 608.v67378e9d3db_1 | Aggregate bundle: Pipeline engine, Declarative, shared libraries, input/milestone, etc. | From Lesson 1 (recommended plugin) |
| Pipeline: Declarative (pipeline-model-definition) | 2.2293.v6e7193cec599 | Declarative syntax and validator | Lessons 1 and 2 |
| Pipeline: Groovy (workflow-cps) | 4403.v471713a_cea_19 | CPS execution engine | Lesson 2 covers the theory |
| Git (git) | 5.11.0 | Git SCM,checkout scm | From Lesson 1 |
| Credentials (credentials) / Credentials Binding (credentials-binding) | 1514.vb_01eb_014e7d4 / 728.v902a_273b_8947 | Credential storage / withCredentials | Module 6 |
| JUnit (junit) | 1458.1460.vd53b_087eeb_2c | Test reports, trends, UNSTABLE | Module 7 (installed automatically as a dependency) |
| Pipeline Graph View (pipeline-graph-view) | 1053.v9df19e6ceed2 | New Pipeline stage view (recommended plugin) | From Lesson 1 |
| Gitea (gitea) | 286.v0740a_413c1eb_ | Gitea server, organization folders, webhooks, commit status | Installed in this module, used in Lesson 2 |
| Docker Pipeline (docker-workflow) | 653.v2f2c08eff0ec | docker.build(),agent { docker … } | Installed in this module, used in Lesson 2 |
| GitHub Branch Source | 1986.v801e40614d00 | GitHub multibranch and organization | Recommended plugin |
| Matrix Authorization Strategy (matrix-auth) | 3.3 | Matrix-based authorization | Lesson 6 |
| Configuration as Code (configuration-as-code) | 2147.v8a_8d38668c72 | JCasC | Lesson 5 |
Changes in 2.580.1: plugins split out of the WAR
Official upgrade guide: from 2.580.1 on 9 “detached plugins” are no longer bundled into jenkins.war (shrinking the WAR by more than 20 MB): bouncycastle API, Command Agent Launcher, Oracle Java SE Development Kit Installer, JAXB, Trilead API, SSH server, JavaBeans Activation Framework (JAF) API, JavaMail API, and Instance Identity. Instances that can reach the Update Center install them automatically when needed; offline instances must place these plugins manually before upgrading. In addition, very old instances upgrading directly from 1.577 or earlier must first install JUnit, Mailer, Matrix Authorization Strategy, Matrix Project and OWASP Markup Formatter.
When: plugin selection checklist
- First check the plugins.jenkins.io listing for Health score, last release date, install count, unresolved security warnings, and whether it is marked deprecated or “up for adoption”.
- If a Pipeline step plus a command-line tool can do the job, do not install another plugin for it (for example, directly
sh 'docker build …'). - UI-related: new instances use Pipeline Graph View (already in the recommended plugins); Blue Ocean still ships maintenance releases (1.27.26), but the project no longer develops new features for it, so new installs are not recommended.
Plugin architecture: extension points and dependencies
Three installation paths
Interactive: plugin dependency resolver (real metadata)
Data comes from the metadata the Update Center provided for core 2.580.2 on 2026-11-16. Tick the plugins you want to install and choose a core version; like the plugin manager, the resolver checks requiredCore → expands required dependencies → excludes parts already installed with the recommended plugins → lists the plugins that will be newly downloaded.
Command table
| Command | Purpose | Key parameters |
|---|---|---|
jcli install-plugin ID… | Install from the Update Center (including dependencies) | -deploy loads immediately; -restart restart after installing; you can also use ID:version |
jcli list-plugins [ID] | List installed plugins; if an update is available, the newer version appears in parentheses after the current version | — |
GET /pluginManager/api/json?depth=1 | Export the plugin list via REST | tree=plugins[shortName,version,active,hasUpdate] |
jenkins-plugin-cli | Plugin Installation Manager (built into the image) | --plugin-file,--plugins,--list,--available-updates |
jcli safe-restart | wait for builds to finish, then restart (needed after uninstalling or downgrading) | — |
Install the Gitea and Docker Pipeline plugins
jcli install-plugin gitea docker-workflow -deploy jcli list-plugins | grep -E '^(gitea|docker-workflow|docker-commons|authentication-tokens) '
Installing gitea from update center Installing docker-workflow from update center gitea Gitea 286.v0740a_413c1eb_ docker-workflow Docker Pipeline 653.v2f2c08eff0ec docker-commons Docker Commons 477.v289085a_b_6896 authentication-tokens Authentication Tokens API 1.144.v5ff4a_5ec5c33
How to verify: Searchable under Manage Jenkins → Plugins → Installed; the “Gitea Organization” item appears when creating a new Item. Common errors:ERROR: Unable to find plugin—— wrong ID (use the short name, such as docker-workflow rather than “Docker Pipeline”). Production use: Emergency installs; routine production changes use plugins.txt.
Export a pinned plugins.txt
cd ~/jenkinslab
curl -s -u "admin:$(cat .secrets/jenkins-token)" \
"http://localhost:8080/pluginManager/api/json?depth=1&tree=plugins[shortName,version]" \
| python3 -c 'import sys,json; [print(f"{p[\"shortName\"]}:{p[\"version\"]}") for p in sorted(json.load(sys.stdin)["plugins"], key=lambda p:p["shortName"])]' \
> plugins.txt
wc -l plugins.txt; grep -E '^(git|gitea|workflow-aggregator|junit):' plugins.txt
97 plugins.txt git:5.11.0 gitea:286.v0740a_413c1eb_ junit:1458.1460.vd53b_087eeb_2c workflow-aggregator:608.v67378e9d3db_1
(production approach) Bake plugins into the image
mkdir -p ~/jenkinslab/controller && cp ~/jenkinslab/plugins.txt ~/jenkinslab/controller/ cat > ~/jenkinslab/controller/Dockerfile <<'EOF' FROM jenkins/jenkins:2.580.2-jdk21 COPY --chown=jenkins:jenkins plugins.txt /usr/share/jenkins/ref/plugins.txt RUN jenkins-plugin-cli --plugin-file /usr/share/jenkins/ref/plugins.txt EOF docker build -t jenkinslab/controller:2.580.2-1 ~/jenkinslab/controller # This lesson does not switch the compose image; Lesson 5 combines this with JCasC (-Djenkins.install.runSetupWizard=false)
ref/ plugins that do not yet exist in JENKINS_HOME into it; existing plugins are not overwritten (unless the file name ends with .override ). So “switching images downgrades plugins” does not necessarily hold for existing volumes; Lesson 5 covers the full procedure.Goal: Install the Gitea and Docker Pipeline plugins, export plugins.txt, and review security and update notices. Environment: Module 2's jcli. Cost: None.
jcli list-plugins | wc -l jcli list-plugins | grep -E '^(workflow-aggregator|git|credentials-binding|pipeline-graph-view|junit|timestamper|ws-cleanup) '
Note that JUnit is not among the 19 recommended plugins, but it is a transitive dependency of them, so it is already installed and the Module 7 junit steps can use it directly.
install-plugin. You can also do this in the UI: Manage Jenkins → Plugins → Available plugins → search for “Gitea” and “Docker Pipeline” → Install.docker global variable documentation.~/jenkinslab/plugins.txt. Lesson 5 uses it to build a controller image with pre-installed plugins.Case 1: a startup failure triggered by one “select all and update”
Problem: An administrator selected all 40 plugins on the Updates page, upgraded them, and restarted. The new version of one plugin required a higher version of a certain API plugin, but that API plugin's upgrade failed (download timed out). On startup Jenkins reported “Failed to load” and disabled a chain of plugins that depended on it, so no Pipeline could run. Action: Restored from backup plugins/; afterward the process changed to: verify on a staging instance → update plugins.txt → build a new image → roll out with a rolling replacement. Constraint: A staging instance that matches production is required.
Case 2: responding to a security advisory
Problem: A security advisory disclosed a CSRF / permission-check vulnerability in a plugin, and some plugins have no fix available yet. Action: Subscribe to the jenkinsci-advisories mailing list; Update Center warnings appear under Manage Jenkins; if a fix exists, upgrade; if none, evaluate disabling the plugin or using an alternative; for high-severity vulnerabilities, first restrict access at the reverse-proxy layer. Constraint: Deprecated plugins will not receive fixes, so the only option is to migrate.
Case 3: governing the number of plugins
Problem: Over the years, the instance accumulated 300+ plugins; startup takes 6 minutes and upgrades carry enormous risk. Action: Export the plugin list and usage (which Job configurations reference each plugin); disable plugins and observe for two weeks before uninstalling; new plugins require review (health score, maintainers, alternatives). Constraint: Plugins used indirectly through step names in a Pipeline are hard to spot in the configuration XML, so you need to scan the Jenkinsfile.
Common errors and fixes
Failed to load: Gitea (gitea 286.v0740a_413c1eb_) - Update required: Git (git 5.4.0) to be updated to 5.10.1 or higher
Cause: A dependency plugin's version is too old (common when .jpi files are placed manually offline, or when only the upper-layer plugin was upgraded).
jcli list-plugins git docker compose logs jenkins | grep -A3 "Failed to load"
Fix: Upgrade the dependencies as prompted (jcli install-plugin git -deploy after jcli safe-restart); in offline environments, use jenkins-plugin-cli resolve the full dependency set on an internet-connected machine and then import it.
Failed to load: JUnit Plugin (junit 1463.v7508416a_349c) - Jenkins (2.589) or higher required
Cause: A latest version built for weekly was uploaded manually (for example, JUnit 1463.v7508416a_349c requires 2.589), while the current core is LTS 2.580.2.
Fix: Install through the Update Center (it offers a compatible version), or specify a compatible version in plugins.txt; or wait for an LTS release that includes that version.
No such DSL method 'docker' found among steps / No such DSL method 'junit'
Cause: The steps used in the Jenkinsfile come from plugins that are not installed or not enabled.
jcli list-plugins | grep -E '^(docker-workflow|junit) '
Fix: Install the corresponding plugin; “Pipeline Syntax → Steps Reference” shows the steps supported by the current instance.
Manage Jenkins shows “You have data stored in an older format and/or unreadable data”
Cause: After uninstalling a plugin, Job configurations still contain that plugin's data.
Fix: Manage Jenkins → Old Data (administrative monitor link): review it and then choose to discard it; or reinstall the plugin.
1. Install the Gitea plugin and load it immediately, without restarting.
jcli install-plugin gitea -deploy
2. Write a Dockerfile based on 2.580.2-jdk21 that pre-installs the plugins in plugins.txt.
FROM jenkins/jenkins:2.580.2-jdk21 COPY --chown=jenkins:jenkins plugins.txt /usr/share/jenkins/ref/plugins.txt RUN jenkins-plugin-cli --plugin-file /usr/share/jenkins/ref/plugins.txt
An offline data center's Jenkins 2.568.3 is to be upgraded to 2.580.2, but after the upgrade it fails to start and the log reports that instance-identity-related classes cannot be found. What is the cause and the correct approach?
Starting with 2.580.1, nine plugins including Instance Identity, bouncycastle API and JavaMail API are no longer bundled into the WAR; internet-connected instances install them automatically, but offline instances cannot find them. The correct approach: before upgrading, read the upgrade guide, and on an internet-connected machine use jenkins-plugin-cli to download these plugins and their dependencies, and place them in JENKINS_HOME/plugins/ then upgrade; or use a custom image with the plugins pre-installed. If it fails, roll back using the backup taken before the upgrade.
Verified teaching videos
No verified video dedicated to “plugin dependencies, the Update Center and jenkins-plugin-cli” was found; please rely on the official documentation and the storyboard below.
official documentation
Video storyboard script (about 80 seconds)
This lesson cannot directly generate a video or MP3, so a storyboard and narration script are provided instead.
Visual: core is a base board with block-like plugins plugged into it, with connecting lines between the blocks.
Narration: Jenkins' capabilities come from plugins; plugins attach to the core through extension points and also depend on one another.
Visual: two versions of the JUnit plugin side by side; the latest one is labeled “requires 2.589”, and the other is labeled “offered for 2.580.2”.
Narration: the Update Center picks compatible versions based on your core version, so LTS users may not see the latest version.
Visual: plugins.txt text scrolls, an arrow points to the Dockerfile, then to the image.
Narration: in production, write plugin versions into plugins.txt and bake them into the image to make the build reproducible.
Visual: a red security advisory card pops up.
Narration: subscribe to security advisories; upgrade if a fix exists, and evaluate disabling the plugin if not.
Module 4 · Job types: Freestyle, Pipeline and Multibranch
- Compare the use cases for Freestyle, Pipeline (inline script / from SCM), Multibranch Pipeline, Organization Folder and Folder.
- Understand where Job configuration is stored
jobs/<name>/config.xml, and be able to export and create Jobs with the CLI. - Understand Multibranch's “branch indexing” mechanism: each branch or PR that contains a Jenkinsfile automatically becomes a child Job.
- Create credentials in the lab
gitea-myappand a Pipeline Jobmyapp(Pipeline script from SCM).
What: main Job (Item) types
| Type | Where configuration lives | Typical use | Limitations |
|---|---|---|---|
| Freestyle project | Jenkins UI (config.xml) | Simple scripts, legacy tasks | Steps are linear “build steps + post-build actions”; no stages, no parallelism, no reviewable code; hard to reuse |
| Pipeline (inline script) | Groovy text box in the Job configuration | Trying out syntax | The script is not in version control; not recommended for long-term use |
| Pipeline (Pipeline script from SCM) | The repository's Jenkinsfile | single-branch CI (this lesson's myapp) | Builds only the configured branch |
| Multibranch Pipeline | Jenkinsfile in each branch / PR | All branches and PRs of one repository | Hands-on in Lesson 2 |
| Organization Folder (Gitea / GitHub Organization) | Scans all repositories in the organization that contain a Jenkinsfile | A platform team onboards dozens or hundreds of repositories at once | Requires the corresponding Branch Source plugin |
| Folder | A container; does not run builds | Organizes Jobs by team; holds folder-level credentials and permissions | — |
| Multi-configuration (Matrix) project | UI | Legacy combinatorial matrix builds | For new projects, use the Declarative matrix (Lesson 2) |
Why: why Pipeline (Pipeline as Code) is the default choice
- Reviewable, traceable: the Jenkinsfile goes through PRs alongside the code, so pipeline changes get the same history and review as code changes.
- Resilient, expressive: stages, parallelism, conditions, retries, manual approval (
input), and timeouts are all language features; a Pipeline can continue after a controller restart (Lesson 2). - Reusable: Shared Libraries extract common logic (Lesson 2).
- Scales to branches: hand the same Jenkinsfile to Multibranch, and every branch and PR automatically gets CI.
How: what a Job looks like on disk
JENKINS_HOME/jobs/
├── hello-freestyle/
│ ├── config.xml ← <project>: builders, publishers, assignedNode
│ ├── nextBuildNumber
│ └── builds/1/{build.xml,log}
└── myapp/
├── config.xml ← <flow-definition>: CpsScmFlowDefinition + GitSCM + scriptPath
└── builds/1/{build.xml,log,workflow/…}
The structure of Multibranch is jobs/myapp-mb/branches/main/…,branches/PR-1/…: child Jobs are automatically created and deleted by branch indexing,do not hand-edit a child Job's configuration, as the next indexing will overwrite it.
When: how to choose
| Situation | Choice |
|---|---|
| New project that needs CI | Multibranch Pipeline (Lesson 2); first learn the syntax with a single-branch Pipeline (this lesson) |
| Platform team onboards an entire organization | Organization Folder + Jenkinsfile convention + Shared Library |
| Ops scheduled scripts (backup, cleanup) | Pipeline + triggers { cron('H 2 * * *') } |
| Many legacy Freestyle jobs | Migrate gradually; to create Jobs in bulk, use Job DSL or JCasC (Lesson 5) |
Where configuration comes from for the four Job types
Two checkouts in Pipeline script from SCM
Interactive: how different Job types react to the same code event
Choose a Job type and a Git event, and observe what Jenkins internally creates or triggers. The mechanism behind Multibranch is branch indexing: the branch source (SCMSource) lists all branches and PRs, creates a child Job for each head that contains a Jenkinsfile, and handles vanished heads according to the orphan strategy.
Command table
| Command | Purpose | Key parameters |
|---|---|---|
jcli list-jobs [folder] | List Jobs | — |
jcli get-job NAME > config.xml | Export Job configuration | Inside a folder, use folder/job |
jcli create-job NAME < config.xml | create a Job from XML | errors if it already exists |
jcli update-job NAME < config.xml | overwrite the configuration | — |
jcli build NAME -s -v | trigger a build, wait, and print the console log | -s wait; -v print the log; -p k=v parameters |
jcli console NAME [N] | view the log of a specific build | -f follow |
Create the Pipeline Job myapp from XML
cd ~/jenkinslab
cat > myapp-job.xml <<'EOF'
<flow-definition plugin="workflow-job">
<description>myapp CI (Lesson 1): Pipeline script from SCM</description>
<keepDependencies>false</keepDependencies>
<definition class="org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition" plugin="workflow-cps">
<scm class="hudson.plugins.git.GitSCM" plugin="git">
<configVersion>2</configVersion>
<userRemoteConfigs>
<hudson.plugins.git.UserRemoteConfig>
<url>http://gitea:3000/lab/myapp.git</url>
<credentialsId>gitea-myapp</credentialsId>
</hudson.plugins.git.UserRemoteConfig>
</userRemoteConfigs>
<branches><hudson.plugins.git.BranchSpec><name>*/main</name></hudson.plugins.git.BranchSpec></branches>
</scm>
<scriptPath>Jenkinsfile</scriptPath>
<lightweight>true</lightweight>
</definition>
<disabled>false</disabled>
</flow-definition>
EOF
jcli create-job myapp < myapp-job.xml
jcli list-jobs
hello-freestyle myapp
How to verify: Open http://localhost:8080/job/myapp/configure, and the Pipeline section shows “Pipeline script from SCM”, the repository URL and the credentials. Common errors: If credentialsId in the XML points to a credential that does not exist, creation succeeds but the build fails with an authentication error. Production use: Put Job XML under version control for disaster recovery; for large-scale generation, use Job DSL / JCasC (Lesson 5).
Export and compare
jcli get-job hello-freestyle | head -n 20
<?xml version='1.1' encoding='UTF-8'?>
<project>
<description>Comparison: Freestyle</description>
<assignedNode>linux</assignedNode>
<canRoam>false</canRoam>
<builders>
<hudson.tasks.Shell>
<command>hostname; python3 --version</command>
Goal: Create a Freestyle Job as a comparison; create the credential gitea-myapp; create the Pipeline Job from XML myapp and observe the failure when “there is no Jenkinsfile yet”. Environment: agent1 is online, and the Gitea repository lab/myapp already has code. Cost: None.
hello-freestyle → Freestyle project → tick Restrict where this project can be run, set Label Expression to linux → add under Build Steps Execute shell: hostname; python3 --version → Save → Build Now. The console should display Building remotely on agent1 (linux docker) in workspace /home/jenkins/agent/workspace/hello-freestyle.| Field | Value |
|---|---|
| Kind | Username with password |
| Scope | Global |
| Username | lab |
| Password | ~/jenkinslab/.secrets/gitea-token content (Gitea access token, not lab's login password) |
| ID | gitea-myapp (the same across the course; referenced by ID in the Jenkinsfile) |
| Description | Gitea user lab token for lab/myapp |
create-job (or in the UI: New Item → myapp → Pipeline → set Definition to Pipeline script from SCM → SCM: Git → Repository URL http://gitea:3000/lab/myapp.git → Credentials: select gitea-myapp → Branch */main → Script Path Jenkinsfile).jcli build myapp -s -v
Started from command line by admin ERROR: Unable to find Jenkinsfile from git http://gitea:3000/lab/myapp.git Finished: FAILURE
This failure proves the controller has already used the credential to access Gitea successfully (otherwise it would be an authentication error). Build again after Module 5 commits the Jenkinsfile.
hello-freestyle Can be deleted (jcli delete-job hello-freestyle), or kept for comparison. Keep myapp the Job and the credential.Case 1: migrating 400 Freestyle Jobs
Problem: Over the years, Freestyle Jobs were copied and pasted between each other, so changing one shared step meant 400 separate edits. Action: First inventory (get-job export all XML for statistics), write the most common patterns as Shared Library steps, then migrate repository by repository to Multibranch + Jenkinsfile; during migration, old Jobs are disabled rather than deleted. Constraint: Some Freestyle plugins (certain post-build actions) have no Pipeline equivalent step and must be replaced.
Case 2: using folders for team isolation
Problem: All teams' Jobs sit flat in the root directory, and credentials are visible globally. Action: One Folder per team; team credentials are stored in folder-level credential stores, and permissions are granted on the folder (Lesson 6). Constraint: Moving a Job changes its URL, so bookmarks and external links need to be updated.
Case 3: automatic onboarding with an Organization Folder
Problem: Every new repository required asking the platform team to create a Job. Action: Use a GitHub / Gitea Organization Folder to scan the organization; any repository containing a Jenkinsfile is onboarded automatically, and webhooks trigger indexing. Constraint: Scan frequency must be balanced against API rate limits (especially noticeable with GitHub).
Common errors and fixes
ERROR: Unable to find Jenkinsfile from git http://gitea:3000/lab/myapp.git
Cause: The file is not on the branch, the Script Path has the wrong case (jenkinsfile), or the branch specifier is wrong (*/master).
git -C ~/jenkinslab/myapp ls-tree --name-only origin/main | grep -i jenkinsfile jcli get-job myapp | grep -E "scriptPath|<name>"
Fix: Commit the Jenkinsfile to main, or correct the Script Path and branch.
stderr: fatal: unable to access 'http://localhost:3000/lab/myapp.git/': Failed to connect to localhost port 3000
Cause: A host address of localhost was used in Jenkins; inside the jenkins/agent1 containers, localhost points to the container itself.
docker compose exec jenkins curl -s -o /dev/null -w "%{http_code}\n" http://gitea:3000/api/v1/version
Fix: Change the repository URL to http://gitea:3000/lab/myapp.git.
stderr: remote: Unauthorized / fatal: Authentication failed for 'http://gitea:3000/lab/myapp.git/'
Cause: The Job did not select a credential (private repository), the credential's password field contains something other than a token or the token has been deleted, or the username is wrong.
curl -s -o /dev/null -w "%{http_code}\n" -u "lab:$(cat ~/jenkinslab/.secrets/gitea-token)" http://localhost:3000/api/v1/repos/lab/myapp
Fix: A 200 response means the token is valid, so check the credential ID the Job selects; a 401 response means regenerate the token and update the credential (Module 6).
Freestyle console: Building on the built-in node / stuck in queue
Cause:“Restrict where this project can be run” was not ticked. When the built-in node has 0 executors, the build waits indefinitely.
Fix: Fill in a label expression linux.
1. Export myapp's configuration to a file and find the credential ID it uses.
jcli get-job myapp > myapp-job.xml grep credentialsId myapp-job.xml
2. Trigger myapp, wait for it to finish, and print the log.
jcli build myapp -s -v
A team has 30 microservice repositories, each with main, several feature branches and PRs. Right now each service has one Freestyle Job that builds only main. How would you design the Jenkins Job structure?
Put a Jenkinsfile in each repository root and common logic in a Shared Library; in Jenkins, create an Organization Folder (GitHub/Gitea Organization) that scans the whole organization and automatically generates a Multibranch for each repository, so branches and PRs get CI automatically; create a folder per team to hold credentials and permissions; use webhooks to trigger indexing; disable the old Freestyle Jobs for a while, then delete them.
Verified teaching videos
official documentation
Video storyboard script (about 70 seconds)
This lesson cannot directly generate a video or MP3, so a storyboard and narration script are provided instead.
Visual: on the left, a Freestyle configuration form; on the right, Jenkinsfile code, with Git commit history beside the code.
Narration: Freestyle's configuration lives in Jenkins, while Pipeline logic lives in the repository, where it can be reviewed and traced back.
Visual: one repository grows three branches and one PR, and Jenkins correspondingly grows four child Jobs.
Narration: a multibranch pipeline uses branch indexing to automatically create child jobs for each branch and PR that contains a Jenkinsfile.
Visual: the controller fetches the Jenkinsfile first, then the agent checks out the whole repository.
Narration: the controller reads the Jenkinsfile first to decide what to do, then the agent checks out the code and does the work.
Module 5 · Your first Jenkinsfile: stage, step and post
- Explain the difference between Declarative and Scripted Pipeline, and know why Declarative is the first choice for new projects.
- Write out the complete structure of
pipeline/agent/options/environment/stages/stage/steps/post. - Master the meaning and execution order of the post conditions (always, changed, fixed, regression, aborted, failure, success, unstable, unsuccessful, cleanup).
- Be able to use
declarative-linterto validate, try changes with Replay, generate snippets with Pipeline Syntax, and understand the difference between single and double quotes.
myapp. Importance:★★★★★What: Jenkinsfile and the two syntaxes
| Declarative | Scripted | |
|---|---|---|
| Top level | pipeline { … } | node { … } |
| Structure | Fixed sections and directives, syntax-checked before execution | Arbitrary Groovy code |
| Readability / barrier to entry | High / low | Depends on the author / requires knowing Groovy |
| Built-in capabilities | automatic checkout,options,post,when,parallel,matrix, per-stage agent, Restart from Stage | all have to be written by hand (try/catch/finally) |
| Escape hatch | script { … } Scripted code can be written inside the block | — |
Both syntaxes run on the same Pipeline engine (CPS). This course uses Declarative throughout, and complex logic goes into Shared Libraries (Lesson 2).
Why: why post and options exist
- Builds without
timeoutcan hang forever, permanently occupying an executor (the queue from Module 1 would get blocked). - Jobs without
buildDiscarderwill pile up all their build records in JENKINS_HOME, and the disk will eventually fill up. postGives “things that must run regardless of success or failure” (collecting test reports, cleaning up the workspace, sending notifications) a fixed place and order.
How: the order of a Declarative run
- The controller lightweight-checks out the Jenkinsfile → parses and validates the syntax (syntax errors fail here, without occupying an agent).
- Top level
agent { label 'linux && docker' }→ submits the queue task, allocates an executor on agent1, and locks the workspace (the lifecycle from Module 1). - Automatic stages Declarative: Checkout SCM: runs in the workspace
checkout scm(can be turned off withoptions { skipDefaultCheckout() }). - Runs each stage's steps in order; if a step fails (for example, if
shreturns a non-zero exit code) → the build result is set to FAILURE, and subsequent stages are skipped. - Post Declarative: Post Actions: conditions are evaluated in a fixed order —
always→changed→fixed→regression→aborted→failure→success→unstable→unsuccessful→cleanup.
| post conditions | When it runs |
|---|---|
always | Always runs |
changed | This result differs from the previous one |
fixed | This build succeeded, and the previous one failed or was unstable |
regression | This build failed, was unstable, or was aborted, and the previous one succeeded |
aborted | Aborted (manually stopped or timed out) |
failure / success / unstable | Result is FAILURE / SUCCESS / UNSTABLE |
unsuccessful | Result is not SUCCESS |
cleanup | Runs after all other conditions, regardless of result (suitable for cleanWs()) |
When: quick reference to common directives
| Directive | Example | Description |
|---|---|---|
agent | agent { label 'linux && docker' },agent none | agent none when each stage declares its own agent |
options | timeout,timestamps(),buildDiscarder,disableConcurrentBuilds(),retry,skipDefaultCheckout() | applies to the whole Pipeline (some can also be used at the stage level) |
environment | APP_NAME = 'myapp' | becomes an environment variable; can also be used credentials('id') (Module 6) |
parameters | string(name: 'TAG', defaultValue: '1.0') | Parameterized builds (Lesson 2) |
triggers | cron('H 2 * * *'),pollSCM('H/5 * * * *'),upstream | currently provides three kinds: cron, pollSCM, upstream |
when | when { branch 'main' } | Conditionally run stages (Lesson 2) |
Quotes: the easiest pitfall to hit
'single quotes'are plain strings,$VARpassed to the shell as-is, and the shell expands environment variables.“double quotes”is a Groovy GString,${env.BUILD_NUMBER}is replaced by Groovy on the controller. Using it forechois convenient, but do not interpolate secrets intosh(Module 6).'''triple single quotes'''Suits multi-line shell scripts.
steps only steps are allowed; variable assignments and loops must go into script { }. ② “The post success condition runs before always”: the order is fixed, with always first and cleanup last. ③ “Every sh runs in a new shell, so a venv activation persists”: on the contrary, each sh each step runs in a new process, so the command that activates the venv and the commands that use it must be written in the same sh step. ④ “If the Jenkinsfile is wrong, you can only commit again”: you can first edit and rerun it online with Replay, and commit once it is confirmed.Jenkinsfile structure diagram
Result state machine
Jenkinsfile line-by-line executor
Choose an outcome and step through to see which line the engine reaches, what appears in the log, and which post blocks run (evaluated in the officially defined order). Assume the previous build was SUCCESS.
Command table
| Command / UI | Purpose | Notes |
|---|---|---|
jcli declarative-linter < Jenkinsfile | Validate Declarative syntax on the controller | Provided by the Pipeline: Declarative plugin |
POST /pipeline-model-converter/validate | Validate via REST | -F "jenkinsfile=<Jenkinsfile" |
| Job → Pipeline Syntax | Snippet Generator, Declarative Directive Generator, Global Variables Reference | Generated from the plugins installed on the current instance |
| Build → Replay | Edit the Jenkinsfile used for this build and rerun it, without committing | Requires Run/Replay permission |
| Build → Restart from Stage | Restart from a stage (Declarative) | Can be turned off with disableRestartFromStage() . |
Your first Jenkinsfile
// ~/jenkinslab/myapp/Jenkinsfile (first version)
pipeline {
agent { label 'linux && docker' }
options {
timestamps()
timeout(time: 10, unit: 'MINUTES')
buildDiscarder(logRotator(numToKeepStr: '20'))
}
environment {
APP_NAME = 'myapp'
}
stages {
stage('Info') {
steps {
echo "Building ${env.APP_NAME} #${env.BUILD_NUMBER} on ${env.NODE_NAME}"
sh 'git log -1 --oneline && python3 --version'
}
}
stage('Test') {
steps {
sh '''
python3 -m venv .venv
. .venv/bin/activate
pip install --quiet -r requirements-dev.txt
python -m pytest -q
'''
}
}
}
post {
always { echo "Result: ${currentBuild.currentResult}" }
success { echo 'Tests passed' }
failure { echo 'Something failed - check the console log' }
}
}
Validate, commit, build
cd ~/jenkinslab/myapp jcli declarative-linter < Jenkinsfile git add Jenkinsfile && git commit -m "ci: first Jenkinsfile" AUTH=$(printf 'lab:%s' "$(cat ../.secrets/gitea-token)" | base64 | tr -d '\n') git -c http.extraHeader="Authorization: Basic $AUTH" push jcli build myapp -s -v
Jenkinsfile successfully validated.
Started from command line by admin
Obtained Jenkinsfile from git http://gitea:3000/lab/myapp.git
[Pipeline] Start of Pipeline
[Pipeline] node
Running on agent1 in /home/jenkins/agent/workspace/myapp
[Pipeline] { (Declarative: Checkout SCM)
[Pipeline] checkout
using credential gitea-myapp
> git fetch --tags --force --progress -- http://gitea:3000/lab/myapp.git +refs/heads/*:refs/remotes/origin/*
Checking out Revision 5c7e2a1… (refs/remotes/origin/main)
[Pipeline] { (Info)
[Pipeline] echo
10:21:07 Building myapp #2 on agent1
[Pipeline] sh
10:21:07 + git log -1 --oneline
10:21:07 5c7e2a1 ci: first Jenkinsfile
10:21:07 + python3 --version
10:21:07 Python 3.13.5
[Pipeline] { (Test)
[Pipeline] sh
10:21:15 .. [100%]
10:21:15 2 passed in 0.21s
[Pipeline] { (Declarative: Post Actions)
[Pipeline] echo
10:21:15 Result: SUCCESS
[Pipeline] echo
10:21:15 Tests passed
[Pipeline] End of Pipeline
Finished: SUCCESS
How to verify: The Job page shows a Pipeline Graph with two stages (Info, Test); build #2 is green. Common errors:WorkflowScript: 3: Invalid agent type … Syntax errors and similar mistakes are reported immediately by the linter and at the start of the build. Production use: Run the linter first in PR checks to avoid merging syntax errors into main.
Goal: Commit the first Jenkinsfile and get a green build; try out Replay, post conditions and timeout. Environment: Module 4's Job myapp, credentials gitea-myapp. Cost: None.
~/jenkinslab/myapp/Jenkinsfile, then run jcli declarative-linter < Jenkinsfile, which should print Jenkinsfile successfully validated.Finished: SUCCESS. In the browser, open the build → view the Pipeline Graph (provided by the recommended Pipeline Graph View plugin), and click each stage to view its log.python -m pytest -q to python -m pytest -q && exit 1 → Run. Observe: the Test stage turns red, post runs always and failure; result FAILURE. Replay does not modify the repository.jcli build myapp -s. This time the previous build was FAILURE and this one is SUCCESS; if you add fixed { echo 'fixed!' } (try it with Replay), it will run.timeout(time: 20, unit: 'SECONDS'), and in Test add sleep 60, and observe Timeout has been exceeded as well as the ABORTED result; the post block for aborted runs.Case 1: a forgotten hung build
Problem: An integration test occasionally hung with no timeout set; over the weekend all executors were occupied, and on Monday every build was queued. Action: Add uniformly through the Shared Library template options { timeout(time: 30, unit: 'MINUTES') }, and add a shorter timeout at the stage level for steps that tend to hang. Constraint: A timeout aborts the Pipeline step; child processes started by sh are usually killed, but background processes that leave the process group (for example nohup) may linger on the agent.
Case 2: disk filled up with build records
Problem: The controller disk is 95% full, mostly with years of build logs and artifacts. Action: Standardize all Jenkinsfiles on buildDiscarder(logRotator(numToKeepStr: '20', artifactNumToKeepStr: '5')); also add a default build discard policy at the global level. Constraint: Builds that audit requires to be kept must use “Keep this build forever” or external archiving.
Case 3: collecting results with post
Problem: Test reports were not published when tests failed, because junit was written after sh, and it no longer runs once sh fails. Action: Move junit into the stage's post { always { … } } (the Module 7 approach). Constraint: junit errors when the report file does not exist; add allowEmptyResults: true.
Common errors and fixes
WorkflowScript: 12: Expected a step @ line 12, column 9.
Cause: Groovy statements were written directly inside steps (for example def x = 1,if).
Fix: Move into script { … }, or use when,environment etc. directives. First use jcli declarative-linter < Jenkinsfile to validate locally.
.venv/bin/activate: No such file / pip: command not found (in the second sh step)
Cause: Each sh is a separate process, and the activate from the previous sh is not preserved; or the agent image does not have python3-venv.
Fix: Write activation and use in the same sh '''…''' step, or directly use .venv/bin/python -m pytest; confirm the agent image installs python3-venv (the Dockerfile from Module 0).
groovy.lang.MissingPropertyException: No such property: BUILD_NUMBER for class: groovy.lang.Binding
Cause: Wrote ${BUILD_NUMBER} in a Groovy string, but in an unsupported context, or misspelled.
Fix: In Groovy, use ${env.BUILD_NUMBER}; in shell, use single quotes around 'echo $BUILD_NUMBER' so the shell expands it. For the list of global variables, see Pipeline Syntax → Global Variables Reference.
Timeout has been exceeded … Finished: ABORTED
Cause: The build exceeded options { timeout(…) }.
Fix: Find the slow step (timestamped log) and fix the root cause of the hang; only raise the timeout if it is truly necessary.
1. Without committing any code, validate the Jenkinsfile syntax on the controller.
jcli declarative-linter < Jenkinsfile
2. Write a post block: print the result regardless of outcome; print fixed only when “recovering from a failure”; finally, clean up the workspace.
post {
always { echo "Result: ${currentBuild.currentResult}" }
fixed { echo 'fixed!' }
cleanup { cleanWs() }
}A colleague's Jenkinsfile puts junit 'reports/*.xml' in the same steps block after sh in the Test stage, and when tests fail, Jenkins shows no failed-test details. Why, and how should it be fixed?
sh returns non-zero because pytest failed, which throws an error, so the later junit in the same steps block no longer runs. Change it by adding, in the Test stage, post { always { junit 'reports/junit.xml' } }, and have pytest generate JUnit XML (--junitxml); going further, you can mark test failures as UNSTABLE instead of FAILURE (Module 7).
Verified teaching videos
official documentation
Video storyboard script (about 80 seconds)
This lesson cannot directly generate a video or MP3, so a storyboard and narration script are provided instead.
Visual: the Jenkinsfile skeleton appears block by block: agent, options, environment, stages, post.
Narration: a Declarative pipeline has a fixed skeleton: first say where and how to run, then list the stages, and finally handle the results.
Visual: a highlighted cursor moves down line by line, while the log on the right scrolls in sync.
Narration: the engine first checks out the code automatically, then runs each stage in turn; each sh is a separate process.
Visual: the ten post conditions are lined up in a column, with always, failure, unsuccessful and cleanup lit up.
Narration: post conditions are evaluated in a fixed order, with always first and cleanup last.
Visual: the terminal runs declarative-linter and shows successfully validated.
Narration: validate before committing, saving a build that would otherwise fail.
Module 6 · Credentials and security basics
- Recognize common credential types, credential stores (system / folder / user) and scopes (Global vs System).
- Know how credentials are encrypted at rest (
credentials.xml+secrets/) and what administrator privileges mean. - Be able to use credentials in a Pipeline in three ways: the SCM's credentialsId,
environment { X = credentials('id') },withCredentials. - Understand the principle and limits of log masking, and avoid the warning "A secret was passed to \"sh\" using Groovy String interpolation"; master the most basic security settings.
gitea-myapp Job created in Module 4. Importance:★★★★★What: credential types
| Kind | Contents | Pipeline binding | Use in this course |
|---|---|---|---|
| Username with password | Username + password/token | usernamePassword; credentials() generates X, X_USR, X_PSW | gitea-myapp (lab + Gitea token),registry-creds (Lessons 3, 4) |
| Secret text | Single string (API token) | string | Webhook secret, Slack token |
| Secret file | Whole file (kubeconfig) | file (bound as a temporary file path) | Lesson 5 |
| SSH Username with private key | Username + private key (+ passphrase) | sshUserPrivateKey | SSH clone, SSH agent |
| Certificate | PKCS#12 certificate | certificate | Client certificate authentication |
| Types provided by plugins | GitHub App, Azure, AWS, Kubernetes service accounts, etc. | Steps from each plugin | Lessons 3–5 |
Stores, domains and scopes
- Stores: system level (Manage Jenkins → Credentials → System),folder level (visible only to Jobs inside that folder; the preferred choice for team isolation), and user level (usable only for operations that user triggers).
- Domain: a hint that groups credentials by hostname or protocol; the default is “Global credentials (unrestricted)”.
- Scope:
GLOBAL—— usable by both Jobs and Jenkins itself;SYSTEM—— for Jenkins' own use only (for example, the controller connecting to agents over SSH, or sending email),builds cannot read it.
How: encrypted storage and decryption
System-level credentials are stored in JENKINS_HOME/credentials.xml, and the password field is ciphertext like {AQAAABAAAA…} . The encryption key secrets/hudson.util.Secret is itself further secrets/master.key encrypted. Conclusion:
- Anyone who gets the entire JENKINS_HOME (including secrets/) can decrypt all credentials; backups must be stored encrypted (Module 2).
- Anyone with Overall/Administer can read any credential through the script console; keep administrators few and precise (Lesson 6).
- Anyone who can modify a Jenkinsfile and run it on a Job that can use the credential can use the credential in a build; so keep credentials in the narrowest possible folder and give tokens minimum permissions.
Three ways to use credentials
| Method | Example | Best for |
|---|---|---|
| credentialsId configured in SCM | Job configuration or git url: …, credentialsId: 'gitea-myapp' | fetching code |
environment + credentials() | GITEA = credentials('gitea-myapp') → $GITEA_USR,$GITEA_PSW | when the whole Pipeline or a specific stage needs it |
withCredentials | withCredentials([usernamePassword(credentialsId: 'gitea-myapp', usernameVariable: 'U', passwordVariable: 'P')]) { sh '…' } | Recommended: smallest scope; exists only within the block |
Log masking: principle and limits
After binding credentials, the Credentials Binding plugin registers these values with the build's log filter, and when the plaintext appears in the log it is replaced with ****. However, it only recognizes the “plaintext”: if a script base64-encodes the token, reverses it, prints it character by character, or writes it to an artifact file, masking cannot stop it. Masking prevents accidental printing, not malicious access.
Why you must not interpolate secrets with double quotes
// ✗ Unsafe: Groovy first substitutes the value of $GITEA_PSW into the command string,
// the plaintext ends up in sh's arguments (visible to ps) and in Pipeline's internal records
sh "curl -u lab:${GITEA_PSW} http://gitea:3000/api/v1/user"
// ✓ Safe: single quotes; the value is passed to the shell only as an environment variable, which the shell expands
sh 'curl -u "lab:$GITEA_PSW" http://gitea:3000/api/v1/user'
Jenkins prints an explicit warning in the log: Warning: A secret was passed to "sh" using Groovy String interpolation, which is insecure.
Post-setup security baseline (covered in depth in Lesson 6)
| Setting | State after setup wizard | Recommendation for this lesson |
|---|---|---|
| Security Realm | Jenkins built-in user database | Keep for the lab; in production, connect SSO (Lesson 6) |
| Authorization | Logged-in users can do anything; anonymous users cannot read | Keep for the lab; in production, switch to matrix or role-based authorization |
| CSRF protection | Enabled (crumb) | Keep; scripts use API tokens |
| Agent → Controller access control | Always enabled (since 2.326) | Keep |
| Built-in node executors | Default 2 | Set to 0 (already done in Module 1) |
| Network exposure | — | Bind only to 127.0.0.1 (done in compose); in production, place it behind a TLS reverse proxy |
Credentials from storage to build steps
Scopes and visibility
Animation: resolution, binding and masking of a single withCredentials call
Choose a form and observe how the Credentials Binding plugin looks up the credential, hands the value to the agent, and what appears in the log.
Command table
| Command | Purpose | Notes |
|---|---|---|
jcli list-credentials system::system::jenkins | List credentials in the system store (does not display secrets) | CLI provided by the Credentials plugin |
jcli create-credentials-by-xml system::system::jenkins _ < cred.xml | Create the credential via XML (_ the global domain) | the XML holds it in plaintext, so delete the file after use |
jcli update-credentials-by-xml system::system::jenkins _ ID < cred.xml | Rotate (update) the credential | the ID stays the same, so jobs need no changes |
jcli delete-credentials system::system::jenkins _ ID | Delete the credential | — |
Create / rotate gitea-myapp via XML
cd ~/jenkinslab umask 077 cat > /tmp/gitea-myapp.xml <<EOF <com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl> <scope>GLOBAL</scope> <id>gitea-myapp</id> <description>Gitea user lab token for lab/myapp</description> <username>lab</username> <password>$(cat .secrets/gitea-token)</password> </com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl> EOF # Created in the UI in Module 4: use update; on a fresh environment, use create jcli update-credentials-by-xml system::system::jenkins _ gitea-myapp < /tmp/gitea-myapp.xml \ || jcli create-credentials-by-xml system::system::jenkins _ < /tmp/gitea-myapp.xml shred -u /tmp/gitea-myapp.xml 2>/dev/null || rm -f /tmp/gitea-myapp.xml jcli list-credentials system::system::jenkins
=========================================================== Domain (global) Description # of Credentials 1 =========================================================== Id Name ================ ========================================== gitea-myapp lab/****** (Gitea user lab token for lab/myapp) ===========================================================
How to verify: It appears under Manage Jenkins → Credentials gitea-myapp, where the password field shows only “Concealed” once opened. Common mistake: The XML heredoc uses the 'EOF' (quoted) delimiter, which causes $(cat …) the variables not to be expanded, so the literal text gets stored. Production use: Token rotation script: generate a new token → update → smoke build → revoke the old token.
Using it in a Pipeline (recommended)
stage('Gitea API') {
steps {
withCredentials([usernamePassword(credentialsId: 'gitea-myapp',
usernameVariable: 'GITEA_USER',
passwordVariable: 'GITEA_TOKEN')]) {
sh '''
curl -sf -u "$GITEA_USER:$GITEA_TOKEN" http://gitea:3000/api/v1/repos/lab/myapp \
| python3 -c 'import sys,json; d=json.load(sys.stdin); print(d["full_name"], "private =", d["private"])'
echo "token is $GITEA_TOKEN" # Masking demo: the log shows ****
'''
}
}
}
[Pipeline] withCredentials
Masking supported pattern matches of $GITEA_TOKEN
[Pipeline] {
[Pipeline] sh
+ curl -sf -u lab:**** http://gitea:3000/api/v1/repos/lab/myapp
lab/myapp private = True
+ echo token is ****
token is ****
[Pipeline] }
Whether the username is also masked depends on the “Treat username as secret” option on the credential; when it is checked, every raw occurrence of “lab” in the log becomes **** (including lab/myapp), so you usually do not need to check it.
Goal: Confirm gitea-myapp, using an inline Pipeline job to demonstrate withCredentials, masking and interpolation warnings, and finally complete one token rotation. Environment: Modules 0–5. Cost: None.
jcli list-credentials system::system::jenkins docker compose exec jenkins grep -A1 "<password>" /var/jenkins_home/credentials.xml | head -n 2
<password>{AQAAABAAAAAwq8c…kM=}</password>cat > ~/jenkinslab/cred-demo.xml <<'EOF'
<flow-definition plugin="workflow-job">
<description>Module 6: credential binding, masking and interpolation warning demo</description>
<definition class="org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition" plugin="workflow-cps">
<script>pipeline {
agent { label 'linux' }
options { skipDefaultCheckout() }
stages {
stage('safe') {
steps {
withCredentials([usernamePassword(credentialsId: 'gitea-myapp', usernameVariable: 'GITEA_USER', passwordVariable: 'GITEA_TOKEN')]) {
sh 'curl -sf -o /dev/null -w "repo api: %{http_code}\\n" -u "$GITEA_USER:$GITEA_TOKEN" http://gitea:3000/api/v1/repos/lab/myapp'
sh 'echo "token is $GITEA_TOKEN"'
}
}
}
stage('unsafe-demo') {
environment { GITEA = credentials('gitea-myapp') }
steps {
sh "echo interpolated ${GITEA_PSW}"
}
}
}
}</script>
<sandbox>true</sandbox>
</definition>
</flow-definition>
EOF
jcli create-job cred-demo < ~/jenkinslab/cred-demo.xml
jcli build cred-demo -s -v | grep -E "repo api|token is|interpolated|Warning|Affected"
repo api: 200 token is **** Warning: A secret was passed to "sh" using Groovy String interpolation, which is insecure. Affected argument(s) used the following variable(s): [GITEA_PSW] interpolated ****
The second stage's output is masked as well, but the warning tells you that the secret has already been passed in plaintext as a command-line argument (on the agent, it can be seen with ps ), and that is the real problem.
cd ~/jenkinslab
docker compose exec -T -u git gitea gitea admin user generate-access-token \
--username lab --token-name jenkins-myapp-$(date +%Y%m%d) --scopes write:repository \
| awk '{print $NF}' > .secrets/gitea-token
# Run update-credentials-by-xml from the “Commands” tab, then:
jcli build cred-demo -s -v | grep "repo api"
# Old token: Gitea web UI → top-right lab → Settings → Applications → delete the token named jenkins-myappjcli delete-job cred-demo; keep gitea-myapp (used by Module 7 and Lesson 2).Case 1: log masking bypassed
Problem: A build script ran env | base64, and the log contained a string that could be decoded into a cloud key, so masking did not work. Fix: Revoke and rotate the key; the Shared Library must not print the full environment; PR builds from external contributors get no credentials at all (the trust policy from Lesson 2 Multibranch). Limitation: Anyone who can modify the Jenkinsfile and use a credential can effectively obtain it, so rely on folder isolation, least privilege and short-lived tokens.
Case 2: a global credential misused by another team
Problem: Team A's deployment token was stored globally; Team B copied a Jenkinsfile that referenced the same ID directly, so the deployment went to Team A's environment. Fix: Migrate to folder-level credentials, combined with folder permissions (Lesson 6). Limitation: During migration, a folder credential with the same ID takes precedence over the global one, so verify in batches.
Case 3: moving from long-lived keys to short-lived identities
Problem: Jenkins holds many long-lived access keys for cloud accounts. Fix: Lessons 3 and 4 switch to managed identities / workload identities and similar approaches, so Jenkins avoids storing long-lived cloud keys where possible. Limitation: Whether it can be fully keyless depends on where the agent runs and on plugin support; Lessons 3 and 4 verify this item by item.
Common errors and fixes
ERROR: Could not find credentials entry with ID 'gitea_myapp'
Cause: wrong ID (underscore / hyphen), the credential is in another folder, or its scope is SYSTEM.
jcli list-credentials system::system::jenkins
Fix: Use consistently gitea-myapp; set the scope of credentials used by builds to Global.
Warning: A secret was passed to "sh" using Groovy String interpolation, which is insecure.
Cause: A double-quoted string uses ${…} to insert the credential variable.
Fix: Switch to single quotes so the shell expands the environment variable: sh 'curl -u "$GITEA_USER:$GITEA_TOKEN" …'.
curl: (22) The requested URL returned error: 401 (calling the Gitea API inside a withCredentials block)
Cause: the token was deleted or expired, or its scope is insufficient (for example, it only has read:user).
curl -s -o /dev/null -w "%{http_code}\n" -H "Authorization: token $(cat ~/jenkinslab/.secrets/gitea-token)" http://localhost:3000/api/v1/repos/lab/myapp
Fix: Generate a new token with the write:repository scope and update the credential.
After restoring credentials.xml, all credentials show as empty / decryption fails
Cause: Only credentials.xml was restored, without restoring secrets/master.key and secrets/hudson.util.Secret.
Fix: Restore the full JENKINS_HOME backup (including secrets/), or re-enter the credentials.
1. List all credential IDs in the system store.
jcli list-credentials system::system::jenkins
2. Write a Pipeline snippet that calls the Gitea API securely using gitea-myapp.
withCredentials([usernamePassword(credentialsId: 'gitea-myapp', usernameVariable: 'U', passwordVariable: 'T')]) {
sh 'curl -sf -u "$U:$T" http://gitea:3000/api/v1/repos/lab/myapp'
}Security audit finding: all teams share one Jenkins, all credentials are in the global domain with Global scope, and many are long-lived personal passwords. Give the remediation order.
① Inventory the credentials and the jobs that reference them; ② replace all personal passwords with scoped tokens for a service account, and set up expiry and a rotation process; ③ create a folder per team and migrate team credentials to folder-level storage, combined with folder permissions; ④ credentials used only by Jenkins itself are set to SYSTEM; ⑤ check interpolation in Jenkinsfiles (warnings in logs) and switch to single quotes; ⑥ gradually move cloud credentials to managed / workload identities (Lessons 3 and 4); ⑦ limit the number of administrators and encrypt backups.
Verified instructional videos
No verified video focused on “Jenkins credential scope, encrypted storage and interpolation warnings” was found. The videos below include segments on credential usage and serve as supplementary material:
Official documentation
Video storyboard script (about 90 seconds)
This courseware cannot directly generate video or MP3, so a storyboard and narration script are provided instead.
Visual: a safe labeled credentials.xml, with a key labeled master.key hanging beside it.
Narration: credentials are encrypted on the controller, and the key is also on the controller, so backups and administrator rights must be strictly protected.
Visual: a withCredentials block opens, and an envelope flies from the controller to the agent, becoming environment variables.
Narration: withCredentials passes the secret to processes on the agent as environment variables, only inside the block.
Visual: the token in the log is starred out; another line with a base64 string is not masked, and a red box flashes.
Narration: log masking only matches the raw text, so changing the encoding gets past it. It guards against accidental printing, not malicious actors.
Visual: double-quoted code is crossed out and replaced with single quotes.
Narration: do not interpolate secrets with double quotes; let the shell expand the environment variables itself.
Module 7 · Build myapp: testing, packaging and archiving
- Pass pytest results to Jenkins as JUnit XML, and understand the difference between FAILURE and UNSTABLE when tests fail and how to choose between them.
- Build and tag the image on agent1
myapp:1.0andmyapp:<build number>, and write OCI labels that record the commit. - Run a smoke test with an in-container health check, and make sure the container is cleaned up even on failure.
- Use
archiveArtifacts+fingerprintto save build information, so you know where the artifacts live on the controller and why the image itself should not be archived.
What: what this CI does
| Stage | What it does | Output | On failure |
|---|---|---|---|
| Declarative: Checkout SCM | Check out main using gitea-myapp | workspace,GIT_COMMIT and similar environment variables | FAILURE (authentication, network) |
| Test | venv + pytest, generating reports/junit.xml | a test report (the Test Result page and trend graph in Jenkins) | FAILURE; later stages are skipped, but the report is still recorded |
| Build image | docker build, tagged myapp:1.0 and myapp:$BUILD_NUMBER | the image in the host's dockerd | FAILURE |
| Smoke test | Run the container and request /healthz | — | FAILURE, and print the container logs |
| Archive | Write reports/build-info.json, archive reports/** and record the fingerprint | artifacts on the controller | FAILURE |
Why: FAILURE or UNSTABLE
Jenkins convention: FAILURE means the build process itself failed (compile errors, step errors); UNSTABLE means the build completed but quality falls short (typically test failures). junit The step sets the result to UNSTABLE when it finds failing test cases. This lesson's choice:
- When pytest fails, make
shreturn a non-zero exit code → FAILURE, so the later Build image stage does not run —no image is built for code that fails its tests. junitPut thepost { always { … } }, so even when it fails, the failing cases still appear on the Test Result page.- If the team wants test failures to show as yellow UNSTABLE and skip later stages, they can use
catchError(buildResult: 'UNSTABLE', stageResult: 'UNSTABLE') { sh '…pytest…' }Pair withoptions { skipStagesAfterUnstable() }. Both approaches are reasonable; what matters is that the whole team is consistent.
How: where artifacts and fingerprints are stored
archiveArtifactsCopy the files in the agent workspace to the controller:JENKINS_HOME/jobs/myapp/builds/N/archive/. So only small files (reports, metadata, binary packages) should be archived,do not archive image tars or large files— images should be pushed to an image registry (Lessons 3 and 4).fingerprint: trueCompute an MD5 for each file and record it inJENKINS_HOME/fingerprints/, so you can trace which jobs and builds a given file appeared in.- Test results are saved in the build directory's
junitResult.xml, and aggregated into a trend graph. - The image itself stays in the host's dockerd (because agent1 uses the host's docker.sock).
docker image ls myappIt is visible on the host.
When: whether to clean the workspace
| Approach | Benefit | Cost |
|---|---|---|
post { cleanup { cleanWs() } } (this lesson) | Every build is clean and is not affected by leftovers from the last build | Recreates the venv and downloads dependencies every time |
| Keep the workspace | Incremental and fast | Leftover files can make a build “pass on CI but fail elsewhere” |
| Dependency cache (pip cache directory, internal PyPI mirror) | Clean and fast | Requires extra configuration (Lesson 7) |
myapp:1.0 Overwriting it each time is fine”— mutable tags cannot be traced, so also apply an immutable myapp:$BUILD_NUMBER and write a revision label.CI pipeline and where artifacts go
Why the smoke test uses docker exec
Stage view simulator
Simulates one build in the Pipeline Graph View. Choose a fault injection and watch which stages change color, which stages are skipped, the final result, and the key console log lines.
Command table
| Step / interface | Purpose | Key parameters |
|---|---|---|
junit | Parse JUnit XML and record test results | testResults,allowEmptyResults |
archiveArtifacts | Copy workspace files to the controller | artifacts,fingerprint,allowEmptyArchive,onlyIfSuccessful |
cleanWs() | Delete the workspace (Workspace Cleanup plugin) | patterns,deleteDirs |
catchError | Catch errors and set the build / stage result | buildResult,stageResult |
GET /job/myapp/lastBuild/testReport/api/json | Read test statistics | tree=passCount,failCount,skipCount |
GET /job/myapp/lastSuccessfulBuild/api/json | List artifacts | tree=number,artifacts[relativePath] |
Complete Jenkinsfile (Lesson 2 continues from this)
// ~/jenkinslab/myapp/Jenkinsfile (full version of Lesson 1)
pipeline {
agent { label 'linux && docker' }
options {
timestamps()
timeout(time: 15, unit: 'MINUTES')
buildDiscarder(logRotator(numToKeepStr: '20', artifactNumToKeepStr: '5'))
disableConcurrentBuilds()
}
environment {
IMAGE = 'myapp'
VERSION = '1.0'
}
stages {
stage('Test') {
steps {
sh '''
python3 -m venv .venv
. .venv/bin/activate
pip install --quiet -r requirements-dev.txt
mkdir -p reports
python -m pytest -q --junitxml=reports/junit.xml
'''
}
post {
always { junit testResults: 'reports/junit.xml', allowEmptyResults: true }
}
}
stage('Build image') {
steps {
sh '''
docker build --pull \
-t "$IMAGE:$VERSION" -t "$IMAGE:$BUILD_NUMBER" \
--label "org.opencontainers.image.revision=$GIT_COMMIT" \
--label "org.opencontainers.image.source=http://gitea:3000/lab/myapp" \
.
'''
}
}
stage('Smoke test') {
steps {
sh '''
CID=$(docker run -d --rm --name "myapp-ci-$BUILD_NUMBER" "$IMAGE:$BUILD_NUMBER")
trap 'docker rm -f "$CID" >/dev/null 2>&1 || true' EXIT
for i in $(seq 1 20); do
if docker exec "$CID" python -c "import urllib.request; urllib.request.urlopen('http://localhost:5000/healthz', timeout=2)" 2>/dev/null; then
echo "healthz OK after ${i}s"; exit 0
fi
sleep 1
done
echo "healthz FAILED"; docker logs "$CID"; exit 1
'''
}
}
stage('Archive') {
steps {
sh '''
docker image inspect "$IMAGE:$BUILD_NUMBER" --format '{{json .}}' \
| python3 -c 'import sys,json,os; d=json.load(sys.stdin); json.dump({"image": os.environ["IMAGE"]+":"+os.environ["VERSION"], "build": os.environ["BUILD_NUMBER"], "id": d["Id"], "revision": os.environ["GIT_COMMIT"], "size": d["Size"]}, open("reports/build-info.json","w"), indent=2)'
cat reports/build-info.json
'''
archiveArtifacts artifacts: 'reports/**', fingerprint: true
}
}
}
post {
success { echo "Built ${env.IMAGE}:${env.VERSION} (also tagged :${env.BUILD_NUMBER})" }
failure { echo 'Build failed - see Test Result and console log' }
cleanup { cleanWs() }
}
}
$GIT_COMMIT from the Declarative automatic checkout (environment variables set by the Git plugin). {{json .}} is a Docker Go template; written inside a single-quoted shell string, it is interpreted by neither Groovy nor the shell.
Verify the build result
JT=$(cat ~/jenkinslab/.secrets/jenkins-token)
curl -s -u "admin:$JT" "http://localhost:8080/job/myapp/lastBuild/testReport/api/json?tree=passCount,failCount,skipCount"; echo
curl -s -u "admin:$JT" "http://localhost:8080/job/myapp/lastSuccessfulBuild/api/json?tree=number,result,artifacts[relativePath]"; echo
docker image ls myapp
docker image inspect myapp:1.0 --format '{{index .Config.Labels "org.opencontainers.image.revision"}}'
{"_class":"hudson.tasks.junit.TestResult","failCount":0,"passCount":2,"skipCount":0}
{"_class":"org.jenkinsci.plugins.workflow.job.WorkflowRun","artifacts":[{"relativePath":"reports/build-info.json"},{"relativePath":"reports/junit.xml"}],"number":4,"result":"SUCCESS"}
REPOSITORY TAG IMAGE ID CREATED SIZE
myapp 1.0 0f3b9c2d7a11 40 seconds ago 171MB
myapp 4 0f3b9c2d7a11 40 seconds ago 171MB
5c7e2a1d9b0e4f3a2c1b8d7e6f5a4b3c2d1e0f9a
Goal: Commit the full Jenkinsfile and build myapp:1.0, run it; then deliberately make one test fail and observe FAILURE and the test report. Environment: Modules 0–6. Cost: None (the image takes about 200 MB of disk).
~/jenkinslab/myapp/Jenkinsfile:
cd ~/jenkinslab/myapp jcli declarative-linter < Jenkinsfile git add Jenkinsfile && git commit -m "ci: test, build image, smoke test, archive" AUTH=$(printf 'lab:%s' "$(cat ../.secrets/gitea-token)" | base64 | tr -d '\n') git -c http.extraHeader="Authorization: Basic $AUTH" push jcli build myapp -s -v | grep -E "passed|Successfully tagged|naming to|healthz|Archiving|Recording|Finished"
10:31:12 2 passed in 0.23s 10:31:12 Recording test results 10:31:40 #8 naming to docker.io/library/myapp:1.0 done 10:31:40 #8 naming to docker.io/library/myapp:4 done 10:31:43 healthz OK after 2s 10:31:44 Archiving artifacts 10:31:44 Recording fingerprints Finished: SUCCESS
docker run -d --rm --name myapp-try -p 127.0.0.1:5000:5000 myapp:1.0 sleep 2; curl -s http://127.0.0.1:5000/healthz; curl -s http://127.0.0.1:5000/ docker rm -f myapp-try
{"status":"ok"}
Hello from 3a9f1c2b7d4e, hits=N/A (redis not connected)reports/build-info.json,reports/junit.xml) → click “See fingerprints” next to a file to see which build produced it.cd ~/jenkinslab/myapp
sed -i 's/{"status": "ok"}/{"status": "degraded"}/' app.py
git commit -am "break: healthz says degraded" && git -c http.extraHeader="Authorization: Basic $AUTH" push
jcli build myapp -s | tail -n 1
curl -s -u "admin:$(cat ../.secrets/jenkins-token)" "http://localhost:8080/job/myapp/lastBuild/testReport/api/json?tree=failCount,passCount"; echo
Completed myapp #5 : FAILURE
{"_class":"hudson.tasks.junit.TestResult","failCount":1,"passCount":1}
The Build image, Smoke test and Archive stages show as skipped (grey), and the Test Result page shows test_healthz the assertion differences.
git revert --no-edit HEAD && git -c http.extraHeader="Authorization: Basic $AUTH" push jcli build myapp -s | tail -n 1
Completed myapp #6 : SUCCESS
myapp:1.0 the image and job; you can delete the numbered tags docker image ls myapp --format '{{.Tag}}' | grep -E '^[0-9]+$' | xargs -r -I{} docker image rm myapp:{}.Case 1: controller disk filled by artifacts
Problem: One job archives 1.2 GB of docker save output each time; three weeks later the controller disk was full and Jenkins refused new builds. Fix: Push images to an image registry, have Jenkins archive only build-info.json, and add artifactNumToKeepStr; clean up old large artifacts with a script. Limitation: Requires an image registry (Lessons 3 and 4).
Case 2: smoke test leaves containers behind
Problem: When the smoke test failed, the script exited early and the test container was not removed; a few days later the host had hundreds of leftover containers holding ports. Fix: Use trap … EXIT to guarantee cleanup, and add --rm, do not map host ports, and clean up periodically docker container prune --filter "label=…". Limitation: If the agent is forcibly killed, the trap will not run either, so periodic cleanup jobs are needed.
Case 3: using fingerprints to trace “who used this build artifact”
Problem: A problematic jar was referenced by several downstream projects, and the blast radius was unknown. Fix: Upstream records fingerprints when archiving; downstream jobs fetch via copyArtifacts and record fingerprints the same way, so Jenkins can show which builds the file appears in. Limitation: Only files recorded through Jenkins fingerprinting can be tracked; tracing container images is better done with image digests + SBOM.
Common errors and fixes
permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock
Cause: The jenkins user in agent1 is not in the group that owns docker.sock (DOCKER_GID in .env is wrong, or the container was not rebuilt after the change).
docker compose exec agent1 sh -c 'id; stat -c "%g %n" /var/run/docker.sock' grep DOCKER_GID ~/jenkinslab/.env
Fix: Change DOCKER_GID to the group ID seen inside the container,docker compose up -d agent1 then rebuild.
ERROR: Step ‘Publish JUnit test result report’ failed: No test report files were found. Configuration error?
Cause: pytest did not generate a report (without adding --junitxml, a path mismatch, or pytest crashing during collection).
Fix: Check that --junitxml=reports/junit.xml matches junit's testResults; when you need to tolerate “no report”, add allowEmptyResults: true (this lesson already includes it).
ModuleNotFoundError: No module named 'app'
Cause: When running pytest directly, the test directory is added to sys.path, but the project root directory is not.
Fix: Use python -m pytest (adds the current directory to the path), or set pythonpath = . in pytest.ini (this lesson does both).
healthz FAILED … [ERROR] Worker failed to boot / ModuleNotFoundError (docker logs output)
Cause: A file is missing from the image (for example, .dockerignore excluded a needed file) or a dependency was not installed.
docker run --rm myapp:1.0 ls /app docker run --rm myapp:1.0 pip list | grep -iE "flask|gunicorn|redis"
Fix: Check the Dockerfile's COPY and .dockerignore (this lesson only COPYs app.py).
1. Use REST to query the number of failed test cases in myapp's most recent build.
curl -s -u "admin:$JT" "http://localhost:8080/job/myapp/lastBuild/testReport/api/json?tree=failCount"
2. Write the steps to archive the reports directory and record its fingerprints.
archiveArtifacts artifacts: 'reports/**', fingerprint: true
The product manager wants “images still built when tests fail, so QA can reproduce.” How would you weigh this and implement it?
By default, releasable images should not be built for code that fails tests. If it is truly needed, use catchError(buildResult: 'UNSTABLE', stageResult: 'UNSTABLE') to wrap the tests so the build continues, and tag the image only with a non-releasable label (such as myapp:ci-$BUILD_NUMBER-unstable), and do not apply 1.0; in the later push / deploy stages add when { expression { currentBuild.currentResult == 'SUCCESS' } } a guard; record the test status in build-info.json.
Verified instructional videos
Official documentation
Video storyboard script (about 90 seconds)
This courseware cannot directly generate video or MP3, so a storyboard and narration script are provided instead.
Visual: five stages laid out horizontally, the Test stage lights up, and pytest outputs two green dots.
Narration: test first, then hand the test report to Jenkins in JUnit format.
Visual: docker build layers complete one by one, and the image gets two tags, 1.0 and the build number.
Narration: build the image only after the tests pass, and apply both a mutable tag and an immutable build-number tag.
Visual: a temporary container starts, a heartbeat icon shows healthz OK, and then the container disappears.
Narration: the smoke test requests the health check from inside the container, and the container is cleaned up afterwards, whether it passed or failed.
Visual: two small files fly back to the controller's filing cabinet, while the image stays in the Docker engine.
Narration: archive only the small reports on the controller; images are pushed to an image registry later.
Module 8 · Build readiness review and troubleshooting basics
- Use the 12-item build readiness review to check the Jenkins instance (architecture, version, plugins, credentials, Jenkinsfile, backup).
- Classify failures by “which step the build is stuck at”: queueing, checkout, step execution, and the platform itself, and know what to check first for each category.
- Collect diagnostic information: console logs, the queue API, node logs, container logs, and the system log (Manage Jenkins → System Log).
- Inject and fix 4 typical faults in the lab.
What: the 12-item build readiness review
| # | Check item | How to verify | Related module |
|---|---|---|---|
| 1 | Use a pinned LTS version tag (2.580.2-jdk21), Java 21/25 | jcli version; compose.yaml | M2 |
| 2 | Built-in node executors = 0 | /computer/api/json in the Built-In Node's numExecutors | M1 |
| 3 | At least one online agent, with labels named by capability | agent1 online, label linux docker | M1 |
| 4 | JENKINS_HOME is on a persistent volume, and there is an encrypted backup that can be restored | docker volume ls; the backup file | M2 |
| 5 | the plugin list has been exported (plugins.txt), with no unresolved security warnings | No red banner at the top of Manage Jenkins | M3 |
| 6 | Job configuration comes from SCM (Jenkinsfile in the repository root) | jcli get-job myapp | M4, M5 |
| 7 | Jenkinsfile has timeout, buildDiscarder, and an explicit agent label | Review the Jenkinsfile; linter passes | M5 |
| 8 | Credentials use a consistent ID (gitea-myapp), and the value is a scope-limited token, not a password | list-credentials | M6 |
| 9 | No interpolated secrets in the Jenkinsfile (no interpolation warnings) | Search the console for “Groovy String interpolation” | M6 |
| 10 | The test report is recorded, and a test failure produces no image | Test Result page; failed builds skip Build image | M7 |
| 11 | Artifacts: only small files are archived, with fingerprints recorded | Build page Build Artifacts | M7 |
| 12 | Exposed only on 127.0.0.1; the docker.sock risk has been recorded and accepted (lab only) | docker compose ps in the PORTS column of | M0, M1 |
Why: first locate “which step it is stuck at”
The Module 1 lifecycle is your troubleshooting map. The stage where the symptom appears determines what to look at:
| Stage | Typical symptom | Check first |
|---|---|---|
| Queue (②–④) | The build spins grey indefinitely; “Still waiting to schedule task” | Hover tooltip on the queue entry / /queue/api/json of why; Nodes page |
| Checkout (⑤) | Authentication failed,Failed to connect,Unable to find Jenkinsfile | first 30 lines of the console; manually run it in the agent container git ls-remote |
| Steps (⑥) | script returned exit code N, permission denied, command not found | Output above the failed step in the console; reproduce the command on the agent |
| Platform | Slow UI, plugin load failures, frequent agent disconnects | Manage Jenkins → System Log; docker compose logs; resource usage |
How: where to find diagnostic information
- Console log:
/job/myapp/N/console, plain text/job/myapp/N/consoleText, CLIjcli console myapp N. - Pipeline step view: Pipeline Graph or
/job/myapp/N/flowGraphTable/(duration and status of each step). - Node log:
/computer/agent1/log(connection log as seen from the controller side) +docker compose logs agent1(agent side). - System log: Manage Jenkins → System Log; the controller container's
docker compose logs jenkins. - System information: Manage Jenkins → System Information (Java, system properties, environment variables, plugin list).
When: when to escalate to “deep troubleshooting”
When a problem is related to load or timing (occasional stalls, steadily growing memory, queues piling up at peak times), you need thread dumps, GC logs and Prometheus metrics; these are covered in Lesson 7. This module addresses “deterministic” configuration and connectivity problems.
Finished: FAILURE the first error, earlier in the log, is the root cause; what follows is mostly a chain reaction.Layered diagram from symptom to root cause
Readiness review coverage
Interactive: build readiness review scorer
Check items one by one against your lab environment. Scores are weighted by risk (security and platform items carry more weight), and failed items show a fix command. Results are saved in this browser.
Command table: diagnostic toolbox
| Command | What it shows |
|---|---|
jcli console myapp [N] | Full console for a given build |
curl …/queue/api/json?tree=items[task[name],why,stuck] | Queue reason |
curl …/computer/api/json?tree=computer[displayName,offline,offlineCauseReason] | Node offline reason |
docker compose logs --since 15m jenkins agent1 gitea | Recent logs for the three services |
docker compose exec agent1 git ls-remote http://gitea:3000/lab/myapp.git | Reproduce checkout from the agent's perspective (prompts when credentials are needed) |
docker system df,docker compose exec jenkins df -h /var/jenkins_home | Disk |
One-step diagnostic collection
cd ~/jenkinslab JT=$(cat .secrets/jenkins-token); OUT=diag-$(date +%H%M%S); mkdir -p "$OUT" docker compose ps > "$OUT/ps.txt" docker compose logs --since 30m > "$OUT/compose.log" 2>&1 curl -s -u "admin:$JT" "http://localhost:8080/queue/api/json?tree=items[id,task[name],why,stuck,inQueueSince]" > "$OUT/queue.json" curl -s -u "admin:$JT" "http://localhost:8080/computer/api/json?tree=computer[displayName,offline,offlineCauseReason,numExecutors,idle]" > "$OUT/nodes.json" curl -s -u "admin:$JT" "http://localhost:8080/job/myapp/lastBuild/consoleText" > "$OUT/last-console.txt" docker compose exec -T jenkins df -h /var/jenkins_home > "$OUT/disk.txt" grep -nE "ERROR|Exception|FAILURE|denied|refused" "$OUT/last-console.txt" | head -n 20 ls "$OUT"
57:permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock 60:ERROR: script returned exit code 1 64:Finished: FAILURE compose.log disk.txt last-console.txt nodes.json ps.txt queue.json
How to verify: All 6 files in the directory are non-empty. Common mistake: queue.json being {"items":[]} is normal (nothing is queued at the moment). Production use: Attach this information when submitting a ticket; note that compose.log and the console may contain sensitive information, so check before sharing.
Goal: Inject 4 faults in turn, and locate and fix each one using this module's methods. Environment: Module 7 completed, with myapp building green. Cost: None. Restore after each fault.
cd ~/jenkinslab docker compose stop agent1 jcli build myapp & # without -s, returns immediately sleep 8; curl -s -u "admin:$(cat .secrets/jenkins-token)" "http://localhost:8080/queue/api/json?tree=items[task[name],why]"; echo
{"_class":"hudson.model.Queue","items":[{"task":{"name":"part of myapp #7"},"why":"‘agent1’ is offline"}]}
Fix:docker compose start agent1, and the build starts automatically a few seconds later. Note that what is queued is “part of myapp #7” — the Pipeline itself has already started (on the controller) and is waiting for agent block's executor.
label 'linux && docker' to label 'linux && dokcer' → Run. The console shows Still waiting to schedule task and There are no nodes with the label ‘linux&&dokcer’ (the label expression is normalized in display). Fix: Stop the build (red cross on the left), and change the label back to the correct one.jcli build myapp -s -v | head -n 30, and see Authentication failed (or the authentication error when the controller reads the Jenkinsfile). Fix: Generate a new token as in Module 6 and update-credentials-by-xml, then rebuild.cd ~/jenkinslab cp .env .env.bak && sed -i 's/^DOCKER_GID=.*/DOCKER_GID=12345/' .env docker compose up -d agent1 && sleep 10 jcli build myapp -s -v | grep -E "permission denied|Finished"
permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: … Finished: FAILURE
Fix:mv .env.bak .env && docker compose up -d agent1, then build again; it should be SUCCESS. Observe: the Test stage passes, and the failure starts at Build image — “look at the first error”.
.env is restored. Keep the environment running, or docker compose stop,do not down -v, as Lesson 2 continues to use it.Case 1: “everything queued” on Monday morning
Problem: All builds were queued, and the UI showed “Waiting for next available executor”. Diagnosis: The queue API showed the same label as the reason for every build; on the Nodes page, all three agents were offline, with the offline reason “Disk space is too low” (the node monitor automatically takes a node offline when disk space falls below the threshold). Fix: Clean up old workspaces and the Docker image cache on the agents, and configure a scheduled cleanup job and disk alerts. Limitation: The node monitor threshold must match the workspace size; a threshold that is too high causes frequent false offline events.
Case 2: intermittent checkout failures
Problem: About 5% of builds failed at checkout, and rerunning them fixed it. Diagnosis: The console showed HTTP 429 / timeouts; the Git server has rate limiting, and multiple jobs were polling SCM at the same time. Fix: Switch to webhook triggers (Lesson 2) and remove the intensive polling; add retry. Limitation: Webhooks require the Git server to be able to reach Jenkins.
Case 3: readiness review built into the change process
Problem: When new teams join the shared Jenkins, they often lack a timeout, hard-code node names, or use personal passwords. Fix: Turn this module's 12-item checklist into an onboarding review template; the Shared Library provides default options; credentials accept only service-account tokens. Limitation: The checklist must be updated regularly as versions and security advisories change.
Interactive troubleshooting tree
Answer questions step by step, starting from the symptom, to get a diagnosis and a fix command. Covers the most common faults in this lesson's lab environment.
Supplement: three most common errors
Still waiting to schedule task / There are no nodes with the label ‘linux&&docker’
Cause: agent1 is offline, or its labels do not include linux and docker.
curl -s -u "admin:$JT" "http://localhost:8080/computer/agent1/api/json?tree=offline,offlineCauseReason,assignedLabels[name]"
Fix: Start agent1 / correct the node labels.
hudson.plugins.git.GitException: Command "git fetch …" returned status code 128
Cause: status 128 is Git's generic failure code; look at the line that follows stderr: saying: authentication, network, or the repository does not exist.
Fix: Follow the Module 4 / 6 troubleshooting entries based on the stderr content.
ERROR: script returned exit code 1
Cause: A sh step's last command (or set -e any command under it) failed. This line itself is not the root cause.
Fix: Look upward for the first error line from that sh; reproduce it by running the same command manually inside the agent container: docker compose exec agent1 bash.
1. Find out with one command why agent1 is offline.
curl -s -u "admin:$JT" "http://localhost:8080/computer/agent1/api/json?tree=offline,offlineCauseReason"
2. Extract all lines containing ERROR from the console of myapp's most recent build.
curl -s -u "admin:$JT" http://localhost:8080/job/myapp/lastBuild/consoleText | grep -n ERROR
A new colleague says: “The myapp build keeps spinning; the log only shows Started by user and Obtained Jenkinsfile, and then nothing happens.” Give the troubleshooting steps.
The Jenkinsfile was read (controller access to Gitea is working), which means it is stuck at the scheduling of the agent block (lifecycle ②–④). ① Check the queue: /queue/api/json of why; ② if it says “no nodes with the label”, check the Jenkinsfile label against agent1's labels; ③ if it says “is offline”: docker compose ps agent1,docker compose logs agent1, check the secret and port 50000; ④ if it says “Waiting for next available executor”, check whether agent1 has a hung build (missing timeout), abort it if necessary and add the timeout; ⑤ once fixed, the build continues automatically, with no need to retrigger.
Verified instructional videos
No verified video focused on “Jenkins build readiness review and troubleshooting methods” was found. Comprehensive supplementary material:
Official documentation
Video storyboard script (about 90 seconds)
This courseware cannot directly generate video or MP3, so a storyboard and narration script are provided instead.
Visual: the Module 1 lifecycle diagram, with its four segments labeled “queue, checkout, steps, platform”.
Narration: when troubleshooting, first ask one question: which segment is the build stuck in?
Visual: the queue entry hover tooltip says is offline; the terminal shows docker compose logs agent1 scrolling.
Narration: for a queued build, check the queue reason and the node logs; most cases are label mismatches or offline nodes.
Visual: console log, scrolling up to find the first red error.
Narration: for failures, look at the first error; the last line is just the result.
Visual: the twelve-item checklist is ticked off one by one, and the score rises above ninety.
Narration: use the twelve-item readiness review to hand the environment over to the next lesson.
Command cheat sheet
Environment lifecycle
cd ~/jenkinslab docker compose up -d jenkins gitea # first time (agent1 needs the secret) docker compose up -d # afterwards docker compose ps docker compose logs -f --since 10m jenkins docker compose stop # pause, keep data docker compose down -v # ⚠ deletes all data
Initialization and identity
docker compose exec jenkins cat /var/jenkins_home/secrets/initialAdminPassword curl -sI http://localhost:8080/login | grep -i '^x-jenkins:' curl -s -u "admin:$(cat .secrets/jenkins-token)" http://localhost:8080/whoAmI/api/json
Jenkins CLI (jcli function)
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/ "$@"; }
jcli version; jcli who-am-i
jcli list-jobs; jcli get-job myapp > myapp.xml
jcli build myapp -s -v; jcli console myapp
jcli safe-restartNodes and queue
J=http://localhost:8080; A="admin:$(cat .secrets/jenkins-token)" curl -s -u "$A" "$J/computer/api/json?tree=computer[displayName,offline,numExecutors,assignedLabels[name]]" curl -s -u "$A" "$J/queue/api/json?tree=items[task[name],why,stuck]" curl -s -u "$A" $J/computer/agent1/jenkins-agent.jnlp # includes secret docker compose logs agent1 | tail
Plugins
jcli install-plugin gitea docker-workflow -deploy jcli list-plugins | grep -E '^(git|gitea|junit) ' curl -s -u "$A" "$J/pluginManager/api/json?depth=1&tree=plugins[shortName,version]" # Dockerfile: RUN jenkins-plugin-cli --plugin-file /usr/share/jenkins/ref/plugins.txt
Credentials
jcli list-credentials system::system::jenkins jcli create-credentials-by-xml system::system::jenkins _ < cred.xml jcli update-credentials-by-xml system::system::jenkins _ gitea-myapp < cred.xml docker compose exec -T -u git gitea gitea admin user generate-access-token \ --username lab --token-name jenkins-myapp --scopes write:repository
Jenkinsfile skeleton
pipeline {
agent { label 'linux && docker' }
options { timestamps(); timeout(time: 15, unit: 'MINUTES')
buildDiscarder(logRotator(numToKeepStr: '20')) }
environment { IMAGE = 'myapp'; VERSION = '1.0' }
stages {
stage('Test') {
steps { sh 'python -m pytest --junitxml=reports/junit.xml' }
post { always { junit 'reports/junit.xml' } }
}
}
post { cleanup { cleanWs() } }
}Credentials and artifact snippets
withCredentials([usernamePassword(credentialsId: 'gitea-myapp',
usernameVariable: 'U', passwordVariable: 'T')]) {
sh 'curl -sf -u "$U:$T" http://gitea:3000/api/v1/repos/lab/myapp'
}
archiveArtifacts artifacts: 'reports/**', fingerprint: true
catchError(buildResult: 'UNSTABLE', stageResult: 'UNSTABLE') { sh '…' }Quick troubleshooting table
| Symptom / error | Most likely cause | First command |
|---|---|---|
| There are no nodes with the label … | Label typo / agent missing label | …/computer/api/json?tree=computer[displayName,assignedLabels[name]] |
| ‘agent1’ is offline | agent container stopped, wrong secret | docker compose logs agent1 |
| Waiting for next available executor | executors exhausted / build hung | Nodes page, to see running builds |
| Failed to connect to localhost port 3000 | localhost used inside the container | change to http://gitea:3000/… |
| Authentication failed | invalid token / wrong credential ID | curl -u lab:TOKEN …/api/v1/repos/lab/myapp |
| Unable to find Jenkinsfile | file not found / wrong branch or path | git ls-tree origin/main |
| permission denied … docker.sock | wrong DOCKER_GID | docker compose exec agent1 id |
| No such DSL method | missing plugin | jcli list-plugins |
| A secret was passed to "sh" using Groovy String interpolation | secret interpolated in double quotes | switch to single-quoted sh |
| Timeout has been exceeded | step stuck | timestamped log to find the slow step |
Recommended configuration snippet: the agent service in compose
agent1:
build: ./agent
init: true
command: ["-url", "http://jenkins:8080", "-workDir=/home/jenkins/agent", "${AGENT1_SECRET:-not-set}", "agent1"]
group_add: ["${DOCKER_GID:-999}"]
volumes:
- agent1_work:/home/jenkins/agent
- /var/run/docker.sock:/var/run/docker.sock # lab only
# If only HTTP(S) can be opened: add "-webSocket" to command
Capstone lab + final quiz
Scenario
A new colleague wants to get the same ~/jenkinslab. You decide to script the configuration of Gitea and Jenkins: only the steps that still have to be done in the browser are kept — “unlock + install suggested plugins + create admin + generate API token + create node” (Lesson 5 automates these too, using JCasC) — everything else is done with commands, and finally an acceptance checklist proves that the environment can be handed over to Lesson 2.
docker compose down -v to delete the existing lab data. If you want to keep the current environment, first back it up following Module 2 jenkins_home, or put the whole lab in another directory (for example ~/jenkinslab2, and change the compose name name and ports).cd ~/jenkinslab docker compose down -v sed -i 's/^AGENT1_SECRET=.*/AGENT1_SECRET=/' .env docker compose up -d jenkins gitea until docker compose logs jenkins 2>&1 | grep -q "Jenkins is fully up and running"; do sleep 3; done docker compose exec jenkins cat /var/jenkins_home/secrets/initialAdminPassword
admin → Jenkins URL http://localhost:8080/ → generate the API token and write it to .secrets/jenkins-token → set Built-In Node executors to 0 → create node agent1 (2 executors,/home/jenkins/agent, label linux docker, only runs matching jobs, inbound connection).cat > ~/jenkinslab/bootstrap.sh <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
cd ~/jenkinslab
J=http://localhost:8080; A="admin:$(cat .secrets/jenkins-token)"
jcli() { docker compose exec -T -e JENKINS_USER_ID=admin -e JENKINS_API_TOKEN="$(cat .secrets/jenkins-token)" \
jenkins java -jar /var/jenkins_home/jenkins-cli.jar -s http://localhost:8080/ "$@"; }
echo "== 1. Jenkins CLI"
docker compose exec -T jenkins curl -sSo /var/jenkins_home/jenkins-cli.jar $J/jnlpJars/jenkins-cli.jar
jcli version
echo "== 2. agent1"
S=$(curl -s -u "$A" $J/computer/agent1/jenkins-agent.jnlp | sed -n 's|.*<argument>\([0-9a-f]\{64\}\)</argument>.*|\1|p')
[ -n "$S" ] || { echo "agent1 node does not exist or has no permission"; exit 1; }
sed -i "s/^AGENT1_SECRET=.*/AGENT1_SECRET=$S/" .env
docker compose up -d agent1
echo "== 3. Gitea users, tokens, repositories
GITEA_PASS=${GITEA_PASS:?export GITEA_PASS first}
until curl -sf http://localhost:3000/api/v1/version >/dev/null; do sleep 2; done
docker compose exec -T -u git gitea gitea admin user create --username lab --password "$GITEA_PASS" \
--email lab@example.com --admin --must-change-password=false || true
docker compose exec -T -u git gitea gitea admin user generate-access-token --username lab \
--token-name "jenkins-myapp-$(date +%s)" --scopes write:repository | awk '{print $NF}' > .secrets/gitea-token
curl -s -o /dev/null -w "create repo: %{http_code}\n" -u "lab:$GITEA_PASS" -H "Content-Type: application/json" \
-X POST http://localhost:3000/api/v1/user/repos -d '{"name":"myapp","private":true,"default_branch":"main"}'
AUTH=$(printf 'lab:%s' "$(cat .secrets/gitea-token)" | base64 | tr -d '\n')
git -C myapp remote set-url origin http://localhost:3000/lab/myapp.git
git -C myapp -c http.extraHeader="Authorization: Basic $AUTH" push -u origin main
echo "== 4. Plugins
jcli install-plugin gitea docker-workflow -deploy
echo "== 5. Credentials gitea-myapp
umask 077
printf '<com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl><scope>GLOBAL</scope><id>gitea-myapp</id><description>Gitea user lab token for lab/myapp</description><username>lab</username><password>%s</password></com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>' \
"$(cat .secrets/gitea-token)" | jcli create-credentials-by-xml system::system::jenkins _
echo "== 6. Job myapp"
jcli create-job myapp < myapp-job.xml
echo "== 7. Build
jcli build myapp -s | tail -n 1
EOF
chmod +x ~/jenkinslab/bootstrap.shread -rsp "Gitea lab password: " GITEA_PASS; echo; export GITEA_PASS ~/jenkinslab/bootstrap.sh
== 1. Jenkins CLI 2.580.2 == 2. agent1 ✔ Container agent1 Started == 3. Gitea users, tokens, repositories create repo: 201 == 4. Plugins == 5. Credentials gitea-myapp == 6. Job myapp == 7. Build Completed myapp #1 : SUCCESS
cd ~/jenkinslab; J=http://localhost:8080; A="admin:$(cat .secrets/jenkins-token)"
curl -s -u "$A" "$J/computer/api/json?tree=computer[displayName,offline,numExecutors]"; echo
curl -s -u "$A" "$J/job/myapp/lastBuild/api/json?tree=number,result,artifacts[relativePath]"; echo
curl -s -u "$A" "$J/job/myapp/lastBuild/testReport/api/json?tree=passCount,failCount"; echo
docker image inspect myapp:1.0 --format '{{.Id}} {{index .Config.Labels "org.opencontainers.image.revision"}}'
curl -s -u "$A" "$J/job/myapp/lastBuild/consoleText" | grep -c "Groovy String interpolation" || truejcli get-job myapp check whether each exists; use update for credentials; continue when repository creation returns 409).Acceptance checklist
Open-ended self-check (6 questions)
1. In your own words, describe the complete path of one myapp build from “Build Now” to “Finished: SUCCESS”, and identify which parts happen on the controller and which on the agent.
controller: receive trigger → queue (quiet period, blocking checks) → lightweight checkout of the Jenkinsfile and parse → submit placeholder task for the agent block → label match to agent1 → allocate executor; agent: lock workspace → checkout scm → run sh (pytest, docker build, smoke test); back on the controller: stream and save logs, copy junit results and archived files to builds/N, evaluate post conditions, write build.xml, release executor.
2. Why does an agent connecting inbound not need to expose any port? In what situations should WebSocket be used instead?
The connection is initiated by the agent: first HTTP discovery, then a connection to the controller's TCP inbound port, after which the channel is bidirectional. Use WebSocket when the controller can only expose HTTPS (for example, behind a load balancer / reverse proxy), which removes the need for port 50000.
3. An LTS user cannot see the latest version of a plugin on the plugins page — is this a bug?
No. The Update Center trims metadata by core version and only offers the highest version compatible with the current core; the newest version may require a newer weekly core (for example, the latest JUnit requires 2.589).
4. Masking already displays the token as ****; why still avoid double-quoted interpolation?
Interpolation concatenates the secret into the command string on the controller and passes it to the agent as plaintext process arguments (ps visible), and it may also appear in Pipeline's internal records; masking only handles raw text in log output. Single quotes keep the secret only as an environment variable.
5. What is the risk of mounting docker.sock on agent1 in this lesson? List two production alternatives.
Anyone who can run commands on agent1 can obtain host root through the Docker daemon. Alternatives: a dedicated build VM as the agent; rootless / isolated Docker (or a dind sidecar, which has a privileged-mode cost); daemonless image build tools; Kubernetes ephemeral Pod agents (Lesson 5).
6. When tests fail, would you make the build FAILURE or UNSTABLE? What are the consequences of each?
FAILURE: later stages are skipped and no image is produced; it is the strongest signal. UNSTABLE: the build continues (can be combined with skipStagesAfterUnstable), suitable for the case where the quality gate should not block but must be visible; however, you must ensure that artifacts from UNSTABLE builds are never released. The team should agree on one convention.
Sources and version notes
| Topic | Verification result | Source (accessed 2026-11-16) |
|---|---|---|
| LTS versions | 2.580.2 (2026-10-28), 2.580.1 (2026-09-30), 2.568.3 (2026-09-02); 2.580.2 includes security fixes | LTS Changelog |
| Weekly versions | 2.590 (2026-11-09), 2.589 (2026-11-01), 2.588 (2026-10-28) | Weekly Changelog; updates.jenkins.io/current/latestCore.txt = 2.590 |
| Java support | Java 25 (from LTS 2.541.1, planned end 2029-09), Java 21 (from 2.479.1, planned end 2027-09); Java 17's last LTS is 2.541.3 and last weekly is 2.544; from 2.555.1, Java 21+ is required | Java Support Policy; LTS Changelog |
| 2.580.x upgrade notes | From 2.580.1, 9 split plugins are no longer bundled in the WAR (bouncycastle API, Command Agent Launcher, JDK Installer, JAXB, Trilead API, SSH server, JAF API, JavaMail API, Instance Identity); direct upgrades from 1.577 and earlier require first installing 5 plugins, including JUnit and Mailer; 2.580.2 has no additional upgrade notes | Upgrade guide 2.580 |
| Docker images | jenkins/jenkins:2.580.2-jdk21,2.580.2-lts-jdk21,-jdk25,-slim,-alpine,-rhel-ubi9-jdk21, Windows ltsc2022/2025 all exist; latest follows weekly; the official Docker install page uses 2.580.2-jdk21; from 2.568.1 there are no Windows 2019 images | Docker Hub jenkins/jenkins;Installing Jenkins: Docker |
| inbound agent image | jenkins/inbound-agent:3395.v6e5377b_0fb_3c-5-jdk21 (2026-11-12); usage -url … [-workDir=…] <secret> <agent name>; environment variables such as JENKINS_URL are now marked deprecated; prefer arguments / REMOTING_OPTS | Docker Hub;README_inbound-agent |
| Controller isolation and executors | Strongly recommended: do not build on the built-in node; builds on the built-in node have the same filesystem access as the Jenkins process; Agent → Controller access control has always been enabled since 2.326; the node documentation recommends setting controller executors to 0; the built-in node was renamed in 2.307 / 2.319.1 | Controller Isolation;Using agents;Built-in node migration |
| Suggested plugins | 19 suggested plugins (platform-plugins.json: cloudbees-folder, antisamy-markup-formatter, build-timeout, credentials-binding, timestamper, ws-cleanup, ant, gradle, workflow-aggregator, github-branch-source, pipeline-github-lib, pipeline-graph-view, git, ssh-slaves, matrix-auth, ldap, email-ext, mailer, dark-theme); calculated against the 2.580.2 Update Center, 92 in total including required dependencies, which include junit | platform-plugins.json; updates.jenkins.io/update-center.actual.json?version=2.580.2 |
| Plugin versions | The Update Center provides for 2.580.2: workflow-aggregator 608.v67378e9d3db_1, pipeline-model-definition 2.2293.v6e7193cec599, workflow-cps 4403.v471713a_cea_19, git 5.11.0, credentials 1514.vb_01eb_014e7d4, credentials-binding 728.v902a_273b_8947, junit 1458.1460.vd53b_087eeb_2c, pipeline-graph-view 1053.v9df19e6ceed2, gitea 286.v0740a_413c1eb_, docker-workflow 653.v2f2c08eff0ec, matrix-auth 3.3, configuration-as-code 2147.v8a_8d38668c72, github-branch-source 1986.v801e40614d00, blueocean 1.27.26; on plugins.jenkins.io, the latest junit 1463.v7508416a_349c and the latest pipeline-graph-view 1134.v63b_71c6f549b_ require core 2.589 | plugins.jenkins.io(API); Update Center JSON |
| Security advisories | Most recent: 2026-10-28 (includes core), 2026-09-16 (plugins only), 2026-09-02 (includes core), 2026-08-05 (includes core) | Security Advisories |
| Declarative syntax | post conditions always, changed, fixed, regression, aborted, failure, success, unstable, unsuccessful, cleanup, executed in this order; triggers only cron, pollSCM, upstream; options list (including timestamps, skipStagesAfterUnstable, disableRestartFromStage) | Pipeline Syntax |
| Gitea | latest 28.4.0 (2026-11-15); starting with 28.0 the “1.” prefix is dropped (formerly 1.28); gitea admin user create and generate-access-token --scopes parameters | Docker Hub gitea/gitea;GitHub releases;Gitea CLI; the version number change comes from third-party reports (linuxiac, alternativeto); the original official blog text could not be found |
| Docker CLI image | docker:29-cli exists (2026-11-16, corresponding to 29.10.0) | Docker Hub docker |
| myapp dependencies | Carried over from the Docker course: flask 3.1.*, redis 5.*, gunicorn 23.*, python:3.13-slim; the latest pytest is 9.2.0 (PyPI), and this lesson uses pytest==9.* | from Lesson 1 of the Docker course;PyPI pytest |
Video verification notes
This lesson lists only videos whose titles and channels were verified via YouTube oEmbed (https://www.youtube.com/oembed?url=…&format=json) on 2026-11-16, with titles and channels verified:
- What Is Jenkins? | What Is Jenkins And How It Works? | Jenkins Tutorial For Beginners | Simplilearn — Simplilearn (Module 1)
- Learn Jenkins! Complete Jenkins Course - Zero to Hero — DevOps Journey (Modules 1, 3)
- Run Jenkins in Docker Container - Jenkins Pipeline Tutorial for Beginners 1/4 — TechWorld with Nana (Module 2)
- How to create Jenkins Pipeline with an Example | Pipeline as Code | Tech Primers — Tech Primers (Modules 4, 5)
- Jenkins Full Course in 4 Hours | Jenkins Tutorial For Beginners | DevOps Training | Edureka — edureka! (Module 4)
- Complete Jenkins Pipeline Tutorial | Jenkinsfile explained — TechWorld with Nana (Modules 5, 6)
- Jenkins Tutorial – How to Deploy a Test Server with Docker + Linux (Full Course) — freeCodeCamp.org (Module 7)
- Jenkins Full Course | Jenkins Tutorial For Beginners | Jenkins Tutorial | Simplilearn — Simplilearn (Modules 7, 8)
oEmbed only verified titles and channels; the videos were not watched segment by segment. The content descriptions in “meta” come from titles and public course outlines and may differ in detail from the videos. Most of these videos were recorded in 2020–2023, so for version numbers, interfaces and security advice (for example, building on the controller, or the old master/slave terminology), follow this lesson. No verifiable dedicated videos were found for plugin dependencies and the Update Center, credential scope and interpolation warnings, or readiness review and troubleshooting methods; the corresponding modules state this and provide storyboard scripts instead.
Voice narration notes
The “Voice” tab uses the browser's built-in Web Speech API to read the Chinese narration script (zh-CN) and the English terms (en-US); it does not depend on the network or external scripts. This courseware cannot embed MP3 or generate video; the narration script and storyboard can be passed to a TTS or video tool to produce audio and video.
Known limitations
- Lab commands have not been run in a real environment: this courseware was written without actually running these commands; all “expected outputs” are examples, and the hashes, IDs, timestamps, build numbers, image sizes, GIDs and Python minor versions in them are illustrative values; console and CLI output formats may differ slightly depending on plugin versions.
gitea admin user generate-access-token's output format (usingawk '{print $NF}'taking the last field) was written based on Gitea's existing behavior; the official documentation gives no output example. If the format differs, copy the token from the output manually. Token scopewrite:repositoryis based on Gitea's token scope naming rules and has not been tested on 28.4.list-credentials,create-credentials-by-xml/update-credentials-by-xmlis a CLI command provided by the Credentials plugin; the output table format is an example. The error text when the lightweight checkout cannot find the Jenkinsfile may differ slightly from the example.- The default value of the “Treat username as secret” option differs depending on how the credential was created and on the plugin version; this lesson makes no assertion about the default.
- The agent image takes the files from
docker:29-clicopies the docker and buildx binaries, based on the official image's directory layout; if the layout changes, you can instead install the Docker official apt repository'sdocker-ce-cli(the approach the official Docker install page uses for the controller). - DOCKER_GID is read from docker.sock's group via a temporary container; this applies to both Linux and Docker Desktop. However, the socket permission behavior of Docker Desktop may differ between versions; if you run into permission problems, see the Docker Desktop documentation.
- The release date and version number of the next LTS baseline (after 2.580) have not been verified; refer to jenkins.io. All version numbers in this lesson are based on data as of 2026-11-16.
- The build lifecycle animation is based on Jenkins Queue's public state model (waiting / blocked / buildable / left) and a simplified implementation of Pipeline placeholder task behavior; it does not cover throttling, locks, cloud node provisioning and similar cases (covered in Lesson 7).