Jenkins Hour 5: Automated Operations — Configuration as Code and Jenkins on Kubernetes
lab, so that every build runs in a disposable Pod- Use JCasC (Configuration as Code plugin) to write every step of the Lesson 1 installation wizard (administrator, authorization, Jenkins URL, agents, credentials, plugins) as
jenkins.yaml, and explain which initialization stage loads it at startup, how multiple files are merged, and how to inject secrets safely. - Use Job DSL and the “seed job” pattern to turn the jobs themselves into code, and understand Job DSL script security, the deletion policy (removedJobAction), and JCasC
jobs:root element. - Design and publish a Shared Library (
vars/,src/,resources/), understand that a “global library is trusted code” and learn to pin versions with Git tags. - Use the official jenkinsci Helm chart in the kind cluster
labnamespacejenkinsto deploy the releasejenkins, and read the StatefulSet, Service, JCasC ConfigMap, and config-reload sidecar that the chart generates. - Use Kubernetes plugin to dynamically create Pod agents for queued builds, and explain step by step: queue → NodeProvisioner → call the Kubernetes API to create the Pod → inbound agent connects back → assign an executor → delete the Pod when the build ends.
- Define a Jenkins backup / restore / upgrade strategy (which parts of JENKINS_HOME must be backed up,
secrets/and why they must not be lost), and use Prometheus metrics and OpenTelemetry plugins to monitor Jenkins and write alerts for queue backlog and executor exhaustion.
1-hour time allocation table
| # | Time | Module | Core content | Animation / interaction | Lab |
|---|---|---|---|---|---|
| 0 | Before class | Setup: kind cluster and Helm | Check ~/jenkinslab (Lessons 1–2), create or reuse a kind cluster lab, install Helm 4, add the jenkins chart repository | Environment self-check checklist | kind get clusters,helm search repo jenkins |
| 1 | 00–06 | Configuration as Code (JCasC) | Root element, loading order (after SYSTEM_CONFIG_LOADED), multi-file merging, secret interpolation ${…}, export, hot reload | Core animation: JCasC reads YAML → validates → configurator writes into the Jenkins object model | Rewrite the wizard configuration as jenkins.yaml, and start a fresh container on port 8082 without the wizard |
| 2 | 06–13 | Job DSL and Seed Jobs | DSL syntax, seed job, JCasC jobs:, script security, removedJobAction, generating multibranch jobs | Seed job generate/delete job simulator | Use DSL to generate a folder + pipeline + myapp multibranch job |
| 3 | 13–21 | Shared Libraries: Reusable Pipelines | Directory structure,@Library, implicit loading, version pinning, trusted vs. sandbox, unit tests | Library resolution and loading animation | Publish to Gitea lab/jenkins-shared-lib and call it from myapp |
| 4 | 21–28 | Run Jenkins on Kubernetes with Helm | chart structure, values, plugin-install init container, JCasC ConfigMap + config-reload sidecar, persistence, RBAC | resources become ready in order after helm install | in the namespace jenkins install the release jenkins |
| 5 | 28–35 | Kubernetes plugin: dynamic Pod agents | cloud / podTemplate,agent { kubernetes { yaml … } },container(), jnlp container, connection method, quotas and cleanup | Core animation: queued build → Pod creation → agent connects back → execution → deletion | myapp's pytest runs in a python:3.13-slim Pod |
| 6 | 35–42 | Backup, restore, and upgrade strategy | JENKINS_HOME structure, secrets, PVC snapshot / tar / thinBackup, RPO/RTO, LTS upgrade process, plugin pinning | Backup scope selector + restore drill | tar backup → delete release → restore → verify |
| 7 | 42–50 | Monitoring Jenkins: metrics, logs, and alerts | Prometheus plugin /prometheus/, ServiceMonitor, key metrics and alerts, OpenTelemetry tracing | queue backlog → alert-firing simulator | kube-prometheus-stack (release kps) scrapes Jenkins |
| 8 | 50–60 | Hours 1–5 recap, self-check, and cleanup | End-to-end chain: commit → scan → shared library → Pod agent → build → metrics; cleanup and cost | End-to-end journey of one commit + troubleshooting tree | Self-check + cleanup (keep the kind cluster for Lessons 6 and 7) |
| — | After class | Cheat sheet · Capstone lab | “Delete Jenkins, rebuild from Git within 30 minutes” | Final quiz (12 questions) | Capstone lab |
Knowledge Coverage Matrix
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands / config | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Describe the entire controller configuration in YAML | ✓ | · | · | ✓ | ✓ | ✓ | ✓ | ✓ | CASC_JENKINS_CONFIG,controller.JCasC.configScripts | M1, M4 |
| Inject secrets safely (not in Git) | ✓ | · | · | ✓ | · | ✓ | · | · | ${VAR},/run/secrets,existingSecret | M1, M4 |
| Jobs as code | · | ✓ | · | ✓ | · | · | · | ✓ | jobs:,pipelineJob,multibranchPipelineJob | M2 |
| Pipeline code reuse and versioning | · | · | ✓ | · | ✓ | · | · | ✓ | @Library('lab-shared@v1.0') _ | M3 |
| Deploy and operate the controller on Kubernetes | · | · | · | ✓ | ✓ | ✓ | ✓ | ✓ | helm upgrade --install jenkins jenkins/jenkins -n jenkins | M4 |
| Elastic build resources (Pod agents) | · | · | · | ✓ | ✓ | · | ✓ | ✓ | agent { kubernetes { … } },container('python') | M5 |
| Backup, restore, upgrade | ✓ | · | · | ✓ | · | ✓ | · | ✓ | tar --exclude=workspace,controller.replicas: 0 | M6 |
| Metrics, tracing, and alerts | · | · | · | · | ✓ | · | ✓ | ✓ | /prometheus/,default_jenkins_executors_queue_length | M7 |
Topics not covered in this lesson (and where to learn them)
| Topic | Why not in this lesson | Where to learn |
|---|---|---|
| Helm itself (template syntax, dependencies, OCI repositories, hooks, tests) | This lesson uses Helm only as an “install tool” | Helm 8-hour course |
| Prometheus / Grafana / Alertmanager internals, PromQL, installing kube-prometheus-stack | This lesson only covers “what Jenkins exposes and what to alert on” | Prometheus & Grafana 8 + 1 hour course |
| kind, Pod, Service, PVC, RBAC basics | Covered in the Kubernetes basics course | Kubernetes 8 + 1 hour course |
| Jenkins authentication (OIDC / SAML / Entra), permission matrix, Script Security approval | Belongs to the security topic | Lesson 6(will reuse this lesson's kind environment) |
| stuck queues, performance tuning, splitting large controllers | Belongs to advanced troubleshooting | Lesson 7 (also reuses this lesson's kind environment) |
| Similar practices in GitHub Actions / Azure Pipelines (reusable workflows, templates) | Different products | GitHub course · Azure DevOps course |
How to use this courseware
Theory · Diagrams · Animation · Commands · Lab · Production cases · Troubleshooting · Quiz · Audio · Video. Read “Theory” and “Animation” first, then do the “Lab”. The animations in Modules 1 and 5 are the core of this lesson.
A quiz score of ≥ 70% or clicking “Mark module complete” counts toward progress, saved in this browser (cleared on refresh if local storage is disabled).
The “Audio” tab uses the browser's built-in Web Speech API (en-US) to read the narration script aloud; if no Chinese voice pack is installed, read the script directly or hand it to another TTS tool.
jenkins latest 5.13.3 (appVersion 2.580.2, default image tag suffix jdk25; to stay consistent with Lesson 1, this lesson switches to 2.580.2-jdk21). Plugin versions are taken from the Jenkins update center: configuration-as-code 2147.v8a_8d38668c72, job-dsl 3732.v9a_c49a_61a_313, kubernetes 4560.vc25b_83890c34, pipeline-groovy-lib 822.vc95f70dea_db_7, prometheus 873.v054598e6e84d, opentelemetry 3.1605.v37c3e29857e5. Plugins are updated frequently, so before you start, check plugins.jenkins.io for the authoritative values.~/jenkinslab using Docker Compose to run jenkins (127.0.0.1:8080),agent1 (label linux docker) and gitea (127.0.0.1:3000, repository lab/myapp). Modules 1–3 of this lesson continue to use this Compose environment; starting with Module 4, switch to the kind cluster lab, and Lessons 6 and 7 will directly reuse the jenkins namespace and release set up in this lesson.Module 0 · Setup: kind cluster and Helm (complete before class)
lab, namespace jenkins and Helm 4- CompletedLesson 1andLesson 2:
~/jenkinslab/compose.yamlcontainsjenkins,agent1,giteathree services; Gitea has users/organizationslaband a repositorylab/myapp(Flask + gunicorn + Redis, port 5000,/healthz, with pytest and a Dockerfile; the Jenkinsfile is at the repository root). - Jenkins already has the credential
gitea-myapp(Gitea username + access token). Cloud resources from Lessons 3 and 4 are unrelated to this lesson and may already have been cleaned up. - Lab machine: Ubuntu 24.04 (Azure VM or local machine) + Docker Engine 29.x, at least 4 vCPUs / 8 GiB free memory (kind 3 nodes + Jenkins controller + several agent Pods).
- Already studied Kubernetes course(kind, Pod, Service, PVC) and Helm course(
helm upgrade --install, values files). This lesson does not repeat these basics.
Step 1: Confirm the Compose lab environment
cd ~/jenkinslab
docker compose ps --format 'table {{.Service}}\t{{.State}}\t{{.Ports}}'
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8080/login
curl -s http://127.0.0.1:3000/api/v1/repos/lab/myapp | python3 -c 'import json,sys;print(json.load(sys.stdin)["full_name"])'
SERVICE STATE PORTS agent1 running gitea running 127.0.0.1:3000->3000/tcp, 22/tcp jenkins running 127.0.0.1:8080->8080/tcp, 127.0.0.1:50000->50000/tcp 200 lab/myapp
If you have already cleaned up the environment, rebuild it following the “Lab environment” section of Lesson 1. docker compose up -d This lesson's Module 1 will start a separate fresh JCasC container (port 8082), and will not change the Lesson 1 jenkins_home volume.
Step 2: kind and kubectl (consistent with the Kubernetes course)
kind version kubectl version --client kind get clusters
kind v0.33.0 go1.2x.x linux/amd64 Client Version: v1.37.1 Kustomize Version: v5.x.x lab
If kind get clusters no lab, follow the Hour 1 section of the Kubernetes course kind-lab.yaml (1 control-plane + 2 workers, node image kindest/node:v1.37.0@sha256:…) and recreate it:
mkdir -p ~/jenkinslab/k8s && cd ~/jenkinslab/k8s cat > kind-lab.yaml <<'EOF' kind: Cluster apiVersion: kind.x-k8s.io/v1alpha4 name: lab nodes: - role: control-plane image: kindest/node:v1.37.0@sha256:a1ed56cfb0e7b93589bdf97c8cd566405a265939e3620fc4f5de89adff580ae5 - role: worker image: kindest/node:v1.37.0@sha256:a1ed56cfb0e7b93589bdf97c8cd566405a265939e3620fc4f5de89adff580ae5 - role: worker image: kindest/node:v1.37.0@sha256:a1ed56cfb0e7b93589bdf97c8cd566405a265939e3620fc4f5de89adff580ae5 EOF kind create cluster --config kind-lab.yaml kubectl config current-context
Creating cluster "lab" ... ✓ Ensuring node image (kindest/node:v1.37.0) 🖼 ✓ Preparing nodes 📦 📦 📦 ... Set kubectl context to "kind-lab" kind-lab
@sha256: reference; the same tag may be rebuilt. If your kind version is not v0.33.0, use the image and digest listed in the release notes for your version.Step 3: Helm 4 and the jenkins chart repository
helm version --short helm repo add jenkins https://charts.jenkins.io helm repo update helm search repo jenkins/jenkins
v4.3.1+g… "jenkins" has been added to your repositories ...Successfully got an update from the "jenkins" chart repository NAME CHART VERSION APP VERSION DESCRIPTION jenkins/jenkins 5.13.3 2.580.2 Jenkins - Build great things at any scale! As t...
The chart is also published in OCI form: oci://ghcr.io/jenkinsci/helm-charts/jenkins (see the chart README). Helm 3.22 can also complete everything in this lesson; for differences between Helm 3 and 4, see Helm course.
Step 4: Namespace and Gitea connectivity (preparing for Modules 3–5)
kubectl create namespace jenkins kubectl create namespace myapp # Let kind nodes (and Pods on them) reach the Compose Gitea by hostname gitea GITEA_CID=$(docker compose -f ~/jenkinslab/compose.yaml ps -q gitea) docker network connect --alias gitea kind "$GITEA_CID" kubectl run nettest --rm -it --restart=Never --image=busybox:1.37 -- wget -qO- http://gitea:3000/api/healthz
namespace/jenkins created
namespace/myapp created
{
"status": "pass",
...
}
pod "nettest" deleted
kind ; the Gitea container is also attached to this network with an alias gitea , so Pod DNS queries are forwarded by CoreDNS to Docker's built-in DNS on the node, which resolves to Gitea. This is a lab technique, not a production practice (in production, the Git server should have a proper domain name and TLS). If resolution fails, you can use docker inspect to look up Gitea's kind IP on the network, use the IP instead, or add hostAliases in podTemplate. busybox:1.37 Check the tags on Docker Hub for the current values.Estimated cost, permissions, and cleanup
- Cost: everything runs on your local machine or lab VM, with no cloud resource charges (if you use an Azure VM, you are billed per VM size; stop or delete the VM when finished).
- Permissions: local Docker permissions and cluster-admin on the kind cluster (kind's default kubeconfig).
- Cleanup: at the end of this lesson keep the kind cluster
laband namespacejenkins; Lessons 6 and 7 continue to use them. For full cleanup, see Module 8.
Self-check checklist
Module 1 · Configuration as Code (JCasC)
jenkins.yaml- Explain JCasC's input (
CASC_JENKINS_CONFIGthe file / directory / URL it points to), when it runs (SYSTEM_CONFIG_LOADEDafterSYSTEM_CONFIG_ADAPTEDand beforeconfig.xml), and its output (in-memory Jenkins objects + files on disk such as - Be fluent with root elements
jenkins/credentials/security/tool/unclassified/jobs, and use the Reference and Schema pages to look up fields. - Use
${VAR}, file secrets (/run/secrets) and^${…}escaping to inject secrets safely; understand the conflict rules for merging multiple files and the limits of hot reload.
What: what JCasC is
Jenkins Configuration as Code (JCasC) is a configuration-as-code plugin that describes the Jenkins controller's system-level configuration (security realm, authorization strategy, nodes and clouds, credentials, tools, and each plugin's global configuration) in human-readable YAML, and applies the YAML to Jenkins' object model at startup or reload. By default it reads $JENKINS_HOME/jenkins.yaml; set the environment variable CASC_JENKINS_CONFIG (or system property casc.jenkins.config) to point at comma-separated files, directories (read recursively for .yml/.yaml), or URLs.
| Root element | What it controls | Corresponding action in the Lesson 1 wizard |
|---|---|---|
jenkins | securityRealm, authorizationStrategy, nodes, clouds, numExecutors, systemMessage, globalNodeProperties… | “Create the first admin user”, add agent1 |
credentials | system-level credentials (domainCredentials) | Add gitea-myapp |
security | Global security settings (such as apiToken, Job DSL script security, Script Approval, and other items provided by plugins) | Some items on the Configure Global Security page |
tool | Tool installations such as Git, JDK, Maven | Tools page |
unclassified | Global configuration of other plugins: location (Jenkins URL),globalLibraries,prometheusConfiguration,openTelemetry… | Jenkins URL in “Instance configuration” |
jobs | Provided by the job-dsl plugin; runs Job DSL scripts to create jobs (Module 2) | Create jobs manually |
Why: why use
- Rebuildable: the controller is broken, you need to migrate to Kubernetes, or you need an identical test instance — one command + one YAML file.
- Reviewable: config changes go through Pull Requests, so it is clear who changed the authorization strategy; far clearer than digging through
config.xmlhistory. - Eliminate “snowflake servers”: manual UI changes are overwritten by the YAML on the next apply (for the parts declared in YAML), and drift is corrected automatically.
- Secrets never land in Git: the YAML only contains
${GITEA_TOKEN}, with values coming from environment variables, files, Kubernetes Secrets, Vault, Azure Key Vault, AWS Secrets Manager, and other SecretSources.
How: how it works
- At startup: the plugin's
ConfigurationAsCode.init()annotated@Initializer(after = SYSTEM_CONFIG_LOADED, before = SYSTEM_CONFIG_ADAPTED)— that is, Jenkins first loads theconfig.xmlfrom disk, then JCasC uses the YAML to override the parts it declares. - Collect sources: parse
CASC_JENKINS_CONFIG, directories are scanned recursively, and multiple files are merged into one tree. The default merge strategy is errorOnConflict: if the same scalar key has different values in two files, it reportsFound conflicting configuration at …; lists are concatenated. - Resolve variables:
${VAR}Passed to SecretSources to resolve in order (environment variables,/run/secrets/VARfiles, optional Vault, etc.), supporting${VAR:-default},${readFile:/path},${base64:…},${json:key:${VAR}},${trim:…}; literal${…}use^${…}escaping. - Configurator: each root element has a RootElementConfigurator; it maps YAML keys to Java classes by
@Symbolor class name (for examplelocal→ built-in user database,globalMatrix→ Matrix authorization strategy), via@DataBoundConstructor/@DataBoundSetterconstructs the object, then calls the corresponding setters andsave()saves to disk. - Unknown fields: when an unrecognized property is encountered, generate
Invalid configuration elements for type: … Available attributes : …; an unrecognized root element (usually because the plugin is not installed) reportsNo configurator found for the following root element: …. - Runtime reload: Manage Jenkins → Configuration as Code → Reload existing configuration; or the CLI
reload-jcasc-configuration; or setCASC_RELOAD_TOKENthen POST/reload-configuration-as-code/?casc-reload-token=…(the Helm chart's config-reload sidecar uses this, Module 4). Only one reload can run at a time; concurrent requests get 409.
When: when to use it and how far to go
- All new instances should start with JCasC; for existing instances, first use the UI to View Configuration / Download Configuration export, then clean it up section by section into hand-written YAML (exported content is not guaranteed to re-import as-is, and often contains default-value noise).
- What JCasC does not do: it does not install plugins (use
plugins.txt+jenkins-plugin-clior Helm'sinstallPlugins); it does not store build history; it does not define jobs itself (leave that tojobs:+ Job DSL).
Comparison with similar approaches
| JCasC YAML | init.groovy.d/*.groovy | Manual UI + backing up config.xml | GitHub Actions / Azure Pipelines | |
|---|---|---|---|---|
| Expression | Declarative; key names come from the plugin's data binding | Imperative Groovy, calling internal APIs | None (relies on people) | SaaS platform, no server to configure |
| Idempotence | Naturally idempotent, can be applied repeatedly | Must be ensured manually | — | — |
| Validatable | Schema,check-configuration | Can only be tried by running it | No | — |
| Risk | YAML must be upgraded in step when a plugin renames a field | Breaks when internal APIs change; scripts have full permissions | Drift, not rebuildable | — |
secrets/), user API tokens, etc. still live in JENKINS_HOME (Module 6). ② “Reload deletes anything not written in the YAML” — No, it only sets the parts that are declared; nodes added manually in the UI still exist after reload (unless you declare the entire nodes list, in which case the list is replaced). ③ “Just put the password directly in the YAML, the repo is private anyway” — anyone who can read the repo or logs can see it; and systemMessage: "${SECRET}" the interpolated values of such “non-protected” fields are shown to all users.Architecture diagram: JCasC inputs, processing, and outputs
Flowchart: Jenkins startup milestones and where JCasC fits
Core animation: how JCasC applies jenkins.yaml to a brand-new controller
Click “Play” or “Next”. Each step highlights the components actually involved, and the terminal shows the matching log line, file, or API. Scenario: the jenkins-casc first container start in the module lab.
Core commands and entry points
| Command / entry point | Purpose | Key points |
|---|---|---|
CASC_JENKINS_CONFIG | Specify YAML sources | comma-separated; directories read recursively; if unset, reads $JENKINS_HOME/jenkins.yaml |
-Djenkins.install.runSetupWizard=false | Skip the install wizard | Place it in JAVA_OPTS; if not set, the wizard still asks for initialAdminPassword |
jenkins-plugin-cli --plugin-file plugins.txt | Install plugins at image build time (JCasC does not install plugins) | one per line id:version; dependencies are resolved automatically |
| Manage Jenkins → Configuration as Code | View / Download Configuration, Reload, Documentation (Reference) | Use exported YAML as a “field dictionary”; do not commit it as-is |
JENKINS_URL/configuration-as-code/schema | JSON Schema for the current instance's plugin combination | can be used for completion / validation in the VS Code YAML extension |
CLI: check-configuration / apply-configuration / export-configuration / reload-jcasc-configuration | validate / apply / export / reload | Requires Overall/Administer |
# Download the CLI matching the controller version, and export the current configuration curl -sO http://127.0.0.1:8082/jnlpJars/jenkins-cli.jar PW=$(cat ~/jenkinslab/casc-lab/secrets/JENKINS_ADMIN_PASSWORD) java -jar jenkins-cli.jar -s http://127.0.0.1:8082/ -auth "admin:$PW" export-configuration > exported.yaml head -20 exported.yaml
jenkins:
authorizationStrategy:
globalMatrix:
entries:
- user:
name: "admin"
permissions:
- "Overall/Administer"
crumbIssuer:
standard:
excludeClientIPFromCrumb: false
disableRememberMe: false
labelAtoms:
- name: "built-in"
...
How to verify: The export contains the field descriptions you declared; apply succeeds. Common errors: The exported YAML contains many default values and auto-generated fields (such as labelAtoms), so committing it as-is makes diffs hard to read and can turn into invalid fields after an upgrade. Production use: When migrating an existing instance, use the export as a reference and hand-write a minimal YAML.
# Validate a new file before applying it (does not change the instance) java -jar jenkins-cli.jar -s http://127.0.0.1:8082/ -auth "admin:$PW" check-configuration < casc/jenkins.yaml && echo OK # After editing the YAML in the mounted directory, hot-reload java -jar jenkins-cli.jar -s http://127.0.0.1:8082/ -auth "admin:$PW" reload-jcasc-configuration
# Reload with a token (this is what the Helm sidecar uses): CASC_RELOAD_TOKEN must be set first printf 'casc-reload-token=%s' "$CASC_RELOAD_TOKEN" > /tmp/reload.tok curl -X POST -G -d @/tmp/reload.tok http://127.0.0.1:8082/reload-configuration-as-code/
Note the trailing slash in the URL. Put the token in a file rather than on the command line, so it does not appear in the ps output (recommended by the official docs).
Lab 1: Rewrite the Lesson 1 install wizard as jenkins.yaml, and start a brand-new controller without the wizard (about 6 minutes)
Goal: start, on 127.0.0.1:8082, a Jenkins equivalent to Lesson 1 but generated entirely from code. Do not modify the Lesson 1 jenkins_home.
mkdir -p ~/jenkinslab/casc-lab/{casc,secrets} && cd ~/jenkinslab/casc-lab
# Use the plugin list exported in Lesson 1 as the basis (wizard's recommended plugins + Gitea + Docker Pipeline, etc.)
cp ~/jenkinslab/plugins.txt plugins.txt
# Append the plugins this lesson needs (if a line with the same name already exists, keep one line)
cat >> plugins.txt <<'EOF'
configuration-as-code:2147.v8a_8d38668c72
matrix-auth:3.3
job-dsl:3732.v9a_c49a_61a_313
EOF
sort -t: -k1,1 -u plugins.txt -o plugins.txt # keep only one line per plugin
grep -cE '^[a-z]' plugins.txt
# Secrets: each file name is the variable name (JCasC's Docker/K8s secrets source)
openssl rand -base64 18 | tr -d '\n' > secrets/JENKINS_ADMIN_PASSWORD
read -rsp 'Gitea token for user lab: ' T; printf '%s' "$T" > secrets/GITEA_TOKEN; echo
chmod 600 secrets/*
echo 'secrets/' >> .gitignorejenkins:
systemMessage: "jenkinslab · managed by JCasC (casc-lab/casc/jenkins.yaml); manual UI changes will be overwritten on reload"
numExecutors: 0 # built-in node runs no builds (Lesson 1 security recommendation)
mode: EXCLUSIVE
securityRealm: # Wizard step 2: create the first admin
local:
allowsSignup: false
users:
- id: "admin"
name: "Lab Admin"
password: "${JENKINS_ADMIN_PASSWORD}"
authorizationStrategy: # The wizard default is 'logged-in users can do anything'; tighten it to a matrix here
globalMatrix:
entries:
- user:
name: "admin"
permissions:
- "Overall/Administer"
- group:
name: "authenticated"
permissions:
- "Overall/Read"
- "Job/Read"
nodes: # agent1 added in Lesson 1 (inbound agent, TCP 50000, 2 executors)
- permanent:
name: "agent1"
labelString: "linux docker"
remoteFS: "/home/jenkins/agent"
numExecutors: 2
launcher:
inbound:
webSocket: false
unclassified:
location: # Wizard step 3: instance configuration (Jenkins URL)
url: "http://127.0.0.1:8082/"
adminAddress: "jenkins-lab@example.com"
credentials: # gitea-myapp added manually in Lesson 1
system:
domainCredentials:
- credentials:
- usernamePassword:
scope: GLOBAL
id: "gitea-myapp"
username: "lab"
password: "${GITEA_TOKEN}"
description: "Access token for the Gitea lab user"
Pipeline job created manually in Lesson 1 myapp (Pipeline script from SCM) moved to a separate file, to make migration in Module 2 easier:
jobs:
- script: >
pipelineJob('myapp') {
description('Lesson 1 myapp job, now generated by JCasC')
definition {
cpsScm {
scm {
git {
remote { url('http://gitea:3000/lab/myapp.git'); credentials('gitea-myapp') }
branch('*/main')
}
}
scriptPath('Jenkinsfile')
}
}
}
If your agent1 uses SSH (jenkins/ssh-agent) instead of the Lesson 1 inbound agent
- permanent:
name: "agent1"
labelString: "linux docker"
remoteFS: "/home/jenkins/agent"
launcher:
ssh:
host: "agent1"
port: 22
credentialsId: "agent1-ssh" # you also need to declare a basicSSHUserPrivateKey in credentials:
sshHostKeyVerificationStrategy:
manuallyTrustedKeyVerificationStrategy:
requireInitialManualTrust: falseFROM jenkins/jenkins:2.580.2-jdk21 ENV JAVA_OPTS="-Djenkins.install.runSetupWizard=false" ENV CASC_JENKINS_CONFIG=/var/jenkins_home/casc_configs COPY --chown=jenkins:jenkins plugins.txt /usr/share/jenkins/ref/plugins.txt RUN jenkins-plugin-cli --plugin-file /usr/share/jenkins/ref/plugins.txt
docker build -t jenkins-casc:2.580.2 .
Step 5/5 : RUN jenkins-plugin-cli --plugin-file /usr/share/jenkins/ref/plugins.txt Done Successfully tagged jenkins-casc:2.580.2
docker run -d --name jenkins-casc \ -p 127.0.0.1:8082:8080 \ -v jenkins_casc_home:/var/jenkins_home \ -v "$PWD/casc:/var/jenkins_home/casc_configs:ro" \ -v "$PWD/secrets:/run/secrets:ro" \ --network jenkinslab_default \ jenkins-casc:2.580.2 docker logs -f jenkins-casc 2>&1 | grep -m1 -E 'Jenkins is fully up and running|ConfigurationAsCode|SEVERE'
2026-11-16 08:12:41.003+0000 [id=34] INFO hudson.lifecycle.Lifecycle#onReady: Jenkins is fully up and running
jenkinslab_default is the Compose project jenkinslab 's default network name; use docker network ls to confirm.
PW=$(cat secrets/JENKINS_ADMIN_PASSWORD) curl -s -u "admin:$PW" http://127.0.0.1:8082/whoAmI/api/json | python3 -m json.tool | grep -E '"name"|"authenticated"' curl -s -u "admin:$PW" 'http://127.0.0.1:8082/computer/api/json?tree=computer[displayName,offline]' curl -s -u "admin:$PW" 'http://127.0.0.1:8082/credentials/store/system/domain/_/api/json?tree=credentials[id]' curl -s -u "admin:$PW" 'http://127.0.0.1:8082/api/json?tree=jobs[name]'
"authenticated": true,
"name": "admin",
{"_class":"hudson.model.ComputerSet","computer":[{"_class":"hudson.model.Hudson$MasterComputer","displayName":"Built-In Node","offline":false},{"_class":"hudson.slaves.SlaveComputer","displayName":"agent1","offline":true}]}
{"_class":"com.cloudbees.plugins.credentials.CredentialsStoreAction$DomainWrapper","credentials":[{"id":"gitea-myapp"}]}
{"_class":"hudson.model.Hudson","jobs":[{"_class":"org.jenkinsci.plugins.workflow.job.WorkflowJob","name":"myapp"}]}
agent1 showing offline is expected: the agent1 in Compose connects to the old controller on 8080. This instance only proves that “configuration can be generated from scratch.”
curl -sO http://127.0.0.1:8082/jnlpJars/jenkins-cli.jar java -jar jenkins-cli.jar -s http://127.0.0.1:8082/ -auth "admin:$PW" reload-jcasc-configuration curl -s -u "admin:$PW" 'http://127.0.0.1:8082/api/json?tree=description'
Refresh the home page; System Message is restored to the value in the YAML. description The field is systemMessage.
docker rm -f jenkins-casc && docker volume rm jenkins_casc_home
secrets/ The directory has been added to .gitignore; put casc/ and plugins.txt,Dockerfile commit to the Gitea repository (for example lab/jenkins-config), and send secrets through another channel (Kubernetes Secret, Vault, etc.).Case 1: 40 controllers unified authorization strategy overnight
Problem: Each team ran its own Jenkins with a patchwork of permissions; audit requires “no anonymous read on any instance; administrators can only be SSO groups”. Approach: The platform team maintains a shared security.yaml (authorizationStrategy + securityRealm), and each instance's CASC_JENKINS_CONFIG points to both the “shared directory + team directory”. Configuration:CASC_JENKINS_CONFIG=/casc/common,/casc/team; team files must not contain securityRealm (checked with yq in CI). Limits: The merge rules report a conflict for the same scalar key, so teams cannot override shared values — exactly the intended effect; lists (such as nodes) are concatenated, so ownership must be agreed on.
Case 2: plugin upgrade causes startup failure
Problem: After upgrading a plugin, the controller exits right after starting, and the log Invalid configuration elements for type …. Approach: The plugin changed a field name. On a staging instance, upgrade the plugin first, export the configuration to compare fields, then update the YAML; put check-configuration into the configuration repo's CI. Limits: JCasC failures block startup (ConfigurationAsCodeBootFailure), which is safer than running with a bad configuration, but upgrades must be verified on staging first (Module 6).
Case 3: rotating secrets without restart
Problem: The Gitea token is rotated every 90 days. Approach: Store the token in a Kubernetes Secret, mount it into /run/secrets, update the Secret, then trigger a JCasC reload,gitea-myapp and the credential is rewritten. Limits: kubelet's sync of mounted Secrets has a delay (mounts using subPath are not updated automatically); a more thorough approach is to use the Kubernetes Credentials Provider or the Vault credentials provider so credentials never enter JENKINS_HOME.
Common errors and fixes
io.jenkins.plugins.casc.ConfiguratorException: No configurator found for the following root element: jobs
Cause: The plugin that provides this root element is not installed or did not load successfully (jobs comes from job-dsl,globalLibraries under unclassified comes from pipeline-groovy-lib).
docker exec jenkins-casc ls /var/jenkins_home/plugins | grep -E 'job-dsl|configuration-as-code' docker logs jenkins-casc 2>&1 | grep -E 'Failed Loading plugin|SEVERE' | head
Fix: Add the plugin to plugins.txt and rebuild the image; if the plugin fails to load because a dependency version is not satisfied, upgrade the dependency or Jenkins as the log suggests.
Invalid configuration elements for type: class hudson.model.Hudson : slaveAgentPorts. Available attributes : …
Cause: Field name typo, or a plugin version update changed the field. The default policy rejects unknown fields.
Fix: Use this instance's Documentation (Reference) page or /configuration-as-code/schema as the reference, or export the current configuration to compare field names. Do not change the unknown-field policy to warn just to “get around” it.
Found conflicting configuration at YamlSource: /var/jenkins_home/casc_configs/team.yaml …
Cause: Multiple files set different values for the same scalar key (for example unclassified.location.url). The Helm chart's default JCasC already sets location, and if you write it again in configScripts there will be a conflict.
grep -rn 'url:' /var/jenkins_home/casc_configs/
Fix: Set each key in only one file; in Helm, set the URL through controller.jenkinsUrl the values, instead of writing it in configScripts location.
Still see the “Unlock Jenkins” install wizard after startup
Cause:JAVA_OPTS is missing -Djenkins.install.runSetupWizard=false, or in compose/helm, overriding JAVA_OPTS causes the value in the image to be lost.
docker exec jenkins-casc sh -c 'echo $JAVA_OPTS'
Fix: Make sure the final effective JAVA_OPTS includes this property; the Helm chart handles it automatically (see Module 4).
Configuration import: Found unresolved variable 'JENKINS_ADMIN_PASSWORD'. Will default to empty string
Cause: The variable is not resolved by any SecretSource: the environment variable does not exist,/run/secrets/JENKINS_ADMIN_PASSWORD and neither does the file (wrong mount path or inconsistent file name casing). At startup JCasC replaces it with an empty string and logs this warning, so the admin login with the expected password fails; a runtime reload in the same situation reports Unable to resolve variable '…'. Aborting configuration reload. and abandons the reload.
docker exec jenkins-casc ls -l /run/secrets/ docker logs jenkins-casc 2>&1 | grep -i unresolved
Fix: Correct the mount; when a default is needed, write ${VAR:-default} (non-secret values only).
1. Without restarting the controller, make the modified jenkins.yaml take effect (give both the CLI method and the token method).
java -jar jenkins-cli.jar -s http://127.0.0.1:8082/ -auth "admin:$PW" reload-jcasc-configuration # Or (if CASC_RELOAD_TOKEN is set) curl -X POST "http://127.0.0.1:8082/reload-configuration-as-code/?casc-reload-token=$CASC_RELOAD_TOKEN"
2. In the YAML, write a shell script argument as a literal ${WORKSPACE}, so that JCasC does not resolve it.
command: "echo ^${WORKSPACE}"JCasC strips the leading ^, and the final configuration keeps ${WORKSPACE}.
A colleague added an agent win1 in the UI; the next day, after you run a JCasC reload,win1 disappeared. Why? How can this be avoided?
Your YAML declares the jenkins.nodes list; JCasC replaces the whole node set with the list, and nodes not in the list are removed. To avoid this: write all nodes in the YAML (recommended), or agree that the UI is read-only — grant Overall/Administer to only a few people, and add a note in System Message: “Managed by JCasC”.
Verified teaching videos
No verified video was found that specifically covers JCasC. The following verified Jenkins comprehensive courses can serve as background review (they do not cover JCasC details; this lesson takes precedence):
Official docs
- Jenkins Handbook: Configuration as Code
- configuration-as-code-plugin (README, demos, docs/features/secrets.adoc, configurationReload.md)
- plugins.jenkins.io: Configuration as Code
Video storyboard (about 90 seconds)
This courseware cannot directly generate video/MP3, but storyboards and narration scripts are provided for use with a video tool.
Visual: on the left, screenshots of the install wizard flash by in sequence (unlock, plugins, admin, URL); on the right, YAML appears line by line in sync.
Narration: every button clicked in the wizard can be written as a few lines in jenkins.yaml.
Visual: a startup milestone timeline; after SYSTEM_CONFIG_LOADED, the JCasC block lights up.
Narration: Jenkins first reads config.xml from disk, then JCasC overrides the parts it declares with YAML. If there is an error, Jenkins refuses to start.
Visual:
${GITEA_TOKEN} variables fly into the /run/secrets folder and turn into asterisks written to credentials.xml.Narration: secrets do not go into Git. The YAML only holds variable names; values come from environment variables, mounted secret files, or Vault.
Visual: someone changes System Message in the UI; after clicking Reload, the text is restored.
Narration: manual drift is corrected by the next reload. Put the YAML under code review, and configuration changes get an audit trail.
Module 2 · Job DSL and Seed Jobs
- Use the Groovy DSL to describe
folder,pipelineJob,multibranchPipelineJob, and know how to check the API Viewer of the current instance. - Understand the “seed job” pattern: one job runs
jobDslsteps that generate, update, and delete other jobs; masterremovedJobAction,lookupStrategy,ignoreExisting. - Understand Job DSL script security (script approval and sandbox), and that inside JCasC
jobs:must be written as${}in^${}.
What: what Job DSL is
Job DSL A plugin that provides a Groovy DSL to describe the configuration of Jenkins jobs (items) in code. After the DSL script runs, the plugin generates config.xml and creates or updates the corresponding item. There are three entry points:
- Seed job: the “Process Job DSLs” build step of a freestyle job, or the
jobDslstep in a pipeline. - JCasC
jobs:Root element:- script:(inline),- file:(local file),- url:(remote file), executed when JCasC applies the configuration. - Jenkins script console (for debugging only).
Why: why jobs should also be code
Dozens of microservices, each with CI, release, and nightly scan jobs; manual copy-paste of UI configuration causes drift, and deleting a service leaves “zombie jobs” behind. Job DSL lets job creation, changes, and deletion go through Pull Requests, and allows bulk generation with loops:
['myapp', 'billing', 'search'].each { svc ->
multibranchPipelineJob("services/${svc}") {
branchSources { git { id("${svc}-git"); remote("http://gitea:3000/lab/${svc}.git"); credentialsId('gitea-myapp') } }
}
}
How: how seed jobs work
- The seed job checks out the DSL repo (such as
lab/jenkins-jobs),jobDsl targets: 'jobs/**/*.groovy'and reads the script. - The plugin executes the DSL in Groovy (under script security control); each
pipelineJob(...)call builds an XML node tree. JobManagementFor each job: if it does not exist, create it; if it exists, compare and update itsconfig.xml(ignoreExisting: truewhen set, skipping existing ones).- The plugin records “which items this seed generated” (Generated Items on the seed job page). On the next run,items generated last time but not declared this time are handled by
removedJobActionthe policy:IGNORE(default) /DISABLE/DELETE. lookupStrategy:JENKINS_ROOT(default, names relative to the root directory) orSEED_JOB(relative to the folder containing the seed job, suitable for “one seed per team folder”).
Script security
When global security is enabled, Job DSL enables script security by default (useScriptSecurity = true): new or modified scripts must be approved by an administrator in In-process Script Approval or run in a restricted sandbox; running in the sandbox requires the seed job to run as a specific user (otherwise it reports “You must configure the DSL job to run as a specific user in order to use the Groovy sandbox.”, usually combined with the Authorize Project plugin). Scripts run via JCasC jobs: are executed from admin-controlled configuration and skip this approval.
When: which approach to choose
| Approach | Suited for | Notes |
|---|---|---|
JCasC jobs: | A few “bootstrap jobs”: folders, the seed job itself, platform jobs | Scripts embedded in YAML; Groovy's ${} must be written as ^${}; every JCasC reload re-executes it |
| Seed job + DSL repo | Many business jobs, team self-service | requires agents and workspaces; configure script security; use removedJobAction to clean up |
| Organization Folder (Gitea/GitHub organization scan) | Standardized teams where “every repository has a Jenkinsfile” | No need to write a DSL for each repository; Job DSL can generate the organization folder itself. |
Comparison with similar technologies
| Job DSL | Jenkins Job Builder (YAML, OpenStack) | GitHub Actions / Azure Pipelines | |
|---|---|---|---|
| Where defined | Groovy running inside Jenkins | External Python tool calling the REST API | YAML per repository; platform auto-discovers |
| Coverage | Almost all plugins (including dynamic DSL) | Depends on JJB's own plugin support | — |
| Deletion handling | removedJobAction | Needs extra scripts | Just delete the YAML |
removedJobAction is IGNORE. ③ “Changes made to generated jobs in the UI persist” — the next seed run overwrites them with the DSL definition (unless ignoreExisting).Architecture diagram: JCasC bootstrap → seed job → business jobs
Data flow: what happens to items during a seed run
Interactive simulator: how a seed job converges the job set
Check the jobs “currently declared” in the DSL repo, choose removedJobAction, then click “Run seed job”. The simulator computes according to the plugin's real logic: create / update / handle according to policy the jobs “generated last time but not declared this time”, and shows the matching log lines from the seed job console.
Core commands and DSL snippets
| Command / location | Purpose | Key parameters / notes |
|---|---|---|
jobDsl Pipeline step | Run DSL in a seed pipeline | targets,scriptText,removedJobAction,removedViewAction,lookupStrategy,sandbox,ignoreExisting,failOnMissingPlugin |
JENKINS_URL/plugin/job-dsl/api-viewer/index.html | DSL APIs available on the current instance (including dynamic DSL) | Plugin versions differ, and available methods differ — the API Viewer is authoritative |
JCasC jobs: - script / file / url | Run DSL at startup / reload | In Groovy, the ${} is written as ^${} |
JCasC security.globalJobDslSecurityConfiguration.useScriptSecurity | Master switch for Job DSL script security | Default true; consider disabling only if the DSL repo is writable by administrators only |
| Manage Jenkins → In-process Script Approval | Approve DSL scripts | Re-approval is required whenever the script content changes |
pipeline {
agent { label 'linux' }
options { disableConcurrentBuilds() }
stages {
stage('Generate jobs') {
steps {
jobDsl targets: 'jobs/**/*.groovy',
removedJobAction: 'DELETE',
removedViewAction: 'DELETE',
lookupStrategy: 'JENKINS_ROOT',
failOnMissingPlugin: true
}
}
}
}
Processing DSL script jobs/myapp.groovy
Added items:
GeneratedJob{name='myapp'}
GeneratedJob{name='myapp/myapp'}
GeneratedJob{name='myapp/nightly-scan'}
Finished: SUCCESS
How to verify: The seed job page shows “Generated Items” on the left, listing the generated jobs; the generated jobs page shows “Seed job: platform/seed”. Common errors:failOnMissingPlugin: false (default), a DSL that references an uninstalled plugin only produces a warning, and the job configuration may be missing blocks. Production use: Turn on failOnMissingPlugin: true and unstableOnDeprecation: true to surface problems early.
folder('myapp') {
displayName('myapp')
description('Generated by platform/seed from lab/jenkins-jobs; do not edit manually')
}
multibranchPipelineJob('myapp/myapp') {
branchSources {
git {
id('lab-myapp') // fixed and unique; changing it rebuilds all branch jobs
remote('http://gitea:3000/lab/myapp.git')
credentialsId('gitea-myapp')
}
}
orphanedItemStrategy {
discardOldItems { numToKeep(10) }
}
}
pipelineJob('myapp/nightly-scan') {
description('Nightly dependency scan')
triggers { cron('H 2 * * *') }
definition {
cps {
sandbox(true)
script('''
pipeline {
agent { label 'linux' }
stages { stage('scan') { steps { echo "scan myapp at ${new Date()}" } } }
}
'''.stripIndent())
}
}
}
Optional: use Gitea's native branch source (supports PR discovery, automatically manages webhooks)
multibranchPipelineJob('myapp/myapp') {
branchSources {
branchSource {
source {
gitea { // dynamic DSL: method names follow this instance's API Viewer
id('lab-myapp')
serverUrl('http://gitea:3000')
repoOwner('lab')
repository('myapp')
credentialsId('gitea-myapp')
traits {
giteaBranchDiscovery { strategyId(1) }
giteaPullRequestDiscovery { strategyId(1) }
}
}
}
}
}
}
Must first be declared in JCasC unclassified.giteaServers.servers (serverUrl http://gitea:3000). For the traits syntax, see the jobs/gitea.yaml.
Lab 2: Bootstrap the seed job with JCasC, and the seed job generates myapp's jobs (about 7 minutes)
Environment: the Module 1 jenkins-casc instance (127.0.0.1:8082, on the same Docker network as Gitea).
cd ~/jenkinslab/casc-lab PW=$(cat secrets/JENKINS_ADMIN_PASSWORD) SECRET=$(curl -s -u "admin:$PW" http://127.0.0.1:8082/computer/agent1/jenkins-agent.jnlp \ | sed -n 's/.*<application-desc><argument>\([0-9a-f]*\)<\/argument>.*/\1/p') docker run -d --name agent-casc --network jenkinslab_default \ jenkins/inbound-agent:latest-jdk21 \ -url http://jenkins-casc:8080/ -name agent1 -secret "$SECRET" -workDir /home/jenkins/agent sleep 15; curl -s -u "admin:$PW" 'http://127.0.0.1:8082/computer/agent1/api/json?tree=offline'
{"_class":"hudson.slaves.SlaveComputer","offline":false}
You can also copy the secret from the node page in the UI. This agent is only for this lab and does not mount the Docker socket.
lab/jenkins-jobs (contents are the Jenkinsfile and jobs/myapp.groovy from the Commands tab):
GT=$(cat secrets/GITEA_TOKEN)
curl -s -X POST -H "Authorization: token $GT" -H 'Content-Type: application/json' \
http://127.0.0.1:3000/api/v1/user/repos -d '{"name":"jenkins-jobs","private":true,"default_branch":"main"}' | grep -o '"full_name":"[^"]*"'
mkdir -p ~/work/jenkins-jobs/jobs && cd ~/work/jenkins-jobs
# After saving the Jenkinsfile and jobs/myapp.groovy from the “Commands” tab to this directory:
git init -b main && git add . && git commit -m "seed: myapp jobs"
git push "http://lab:$GT@127.0.0.1:3000/lab/jenkins-jobs.git" main
"full_name":"lab/jenkins-jobs" * [new branch] main -> main
myapp: the DSL will turn myapp into a folder (containing a multibranch job) that conflicts with the root-level pipeline job of the same name. First remove it from JCasC and delete it (a JCasC reload does not automatically delete jobs):
mv casc/jobs-hour1.yaml ~/jenkinslab/casc-lab/jobs-hour1.yaml.retired java -jar ~/jenkinslab/casc-lab/jenkins-cli.jar -s http://127.0.0.1:8082/ -auth "admin:$PW" delete-job myapp
casc/jobs.yaml (a separate file, showing multi-file merging):
security:
globalJobDslSecurityConfiguration:
useScriptSecurity: false # only because lab/jenkins-jobs can only be pushed to by administrators; see the note below
jobs:
- script: >
folder('platform') { description('Platform jobs, created by JCasC') }
- script: >
pipelineJob('platform/seed') {
description('Seed job: runs the Job DSL in lab/jenkins-jobs')
definition {
cpsScm {
scm {
git {
remote { url('http://gitea:3000/lab/jenkins-jobs.git'); credentials('gitea-myapp') }
branch('*/main')
}
}
scriptPath('Jenkinsfile')
}
}
}
java -jar ~/jenkinslab/casc-lab/jenkins-cli.jar -s http://127.0.0.1:8082/ -auth "admin:$PW" reload-jcasc-configuration java -jar ~/jenkinslab/casc-lab/jenkins-cli.jar -s http://127.0.0.1:8082/ -auth "admin:$PW" list-jobs platform
seed
java -jar ~/jenkinslab/casc-lab/jenkins-cli.jar -s http://127.0.0.1:8082/ -auth "admin:$PW" build platform/seed -s -v | tail -8 java -jar ~/jenkinslab/casc-lab/jenkins-cli.jar -s http://127.0.0.1:8082/ -auth "admin:$PW" list-jobs myapp
Processing DSL script jobs/myapp.groovy
Added items:
GeneratedJob{name='myapp'}
GeneratedJob{name='myapp/myapp'}
GeneratedJob{name='myapp/nightly-scan'}
Finished: SUCCESS
Completed platform/seed #1 : SUCCESS
myapp
nightly-scan
Multibranch job myapp/myapp After creation it automatically scans branches and creates child jobs for main (using the Jenkinsfile at the repo root, written in Lesson 2).
jobs/myapp.groovy delete the nightly-scan definition, commit and push, then run the seed:
Processing DSL script jobs/myapp.groovy
Unreferenced items:
GeneratedJob{name='myapp/nightly-scan'}
Removed items:
GeneratedJob{name='myapp/nightly-scan'}docker rm -f agent-casc # If you no longer need the 8082 instance: docker rm -f jenkins-casc && docker volume rm jenkins_casc_home
Case 1: standardizing jobs for 200 microservices
Problem: Each service's jobs are created manually by each team, with different build retention, triggers, and credentials. Approach: The platform team maintains a jenkins-jobs repository, using a services.yaml that lists the service names and teams; the DSL reads it (readFileFromWorkspace) and loops to generate multibranch jobs; a new service going live = change one line of YAML and open a PR. Limits: The DSL repo becomes a high-privilege entry point and needs a protected branch + CODEOWNERS; seed run time grows with the number of jobs, so split into multiple seeds per team (lookupStrategy: SEED_JOB).
Case 2: accidental deletion causes loss of build history
Problem: Someone refactored the DSL and changed a folder name; the seed was run with DELETE so all jobs under the old path were deleted along with their build history. Approach: Change to DISABLE and add a “pre-check” stage to the seed pipeline: first use removedJobAction: 'IGNORE' to run a dry-run-style comparison (count the Unreferenced items), failing if the threshold is exceeded; for renames, use the moved approach — create new, migrate, then delete. Limits: Job DSL has no real dry-run mode; you can run it first on a test instance.
Case 3: organization folder replaces per-repo DSL
Problem: The team wants “creating a new repo with a Jenkinsfile automatically gets CI”. Approach: Use a DSL snippet to generate a Gitea organizationFolder (a complete example is in the JCasC demos), and let the organization scan discover repositories automatically. Limits: Cannot customize job properties for individual repositories; needs a Shared Library (Module 3) to standardize pipeline content.
Common errors and fixes
ERROR: script not yet approved for use
Cause: Job DSL script security is enabled, and the script is new or modified and has not been approved.
Fix: An administrator approves it in Manage Jenkins → In-process Script Approval; or enable the sandbox (requires the seed job to run as a specified user); or, under strict control, disable it via JCasC useScriptSecurity.
You must configure the DSL job to run as a specific user in order to use the Groovy sandbox.
Cause:sandbox: true, but the build runs as SYSTEM.
Fix: Install the Authorize Project plugin, and configure the seed job to run as the triggering user or a specified service account (Lesson 6 covers authorization in detail).
No signature of method: javaposse.jobdsl.dsl.helpers.… is applicable for argument types …
Cause: The DSL method used does not exist in the current plugin version (online examples come from different versions, or the corresponding plugin is not installed).
curl -s -u "admin:$PW" http://127.0.0.1:8082/plugin/job-dsl/api-viewer/index.html -o /dev/null -w '%{http_code}\n'
Fix: Open this instance's API Viewer and search for the correct method; the method names for dynamic DSL come from the plugin's @Symbol/ class names.
The DSL generated in JCasC produced a string missing a value, such as “scan myapp at ”
Cause: JCasC performed ${…} variable substitution before running the DSL, so Groovy interpolation was replaced with an empty string early.
Fix: In JCasC's jobs: - script: write ^${…}; or put the DSL in a standalone .groovy file and run it with a seed job (recommended).
All branch sub-jobs of the multibranch job are rebuilt after every seed run, and build numbers start from 1
Cause:branchSources does not set a fixed id (or randomly generated each time), so the branch source is treated as new.
Fix: Set a stable, unique id('…').
1. Write a jobDsl step: read teams/**/*.groovy, names relative to the seed job's folder; retired jobs are only disabled, not deleted.
jobDsl targets: 'teams/**/*.groovy', lookupStrategy: 'SEED_JOB', removedJobAction: 'DISABLE'
2. Use the CLI to trigger the seed job, wait for the result, and print the console output.
java -jar jenkins-cli.jar -s http://127.0.0.1:8082/ -auth "admin:$PW" build platform/seed -s -v
A developer has write access to the jenkins-jobs repo, and Job DSL script security is turned off. What risk does this mean? Give two safer options.
The developer can write arbitrary Groovy in the DSL (for example, read secrets/, call Jenkins.get() to modify the security configuration), executing as SYSTEM on the controller, which is equivalent to admin rights. Options: ① keep useScriptSecurity=true, enable the sandbox, and use Authorize Project to run the seed as a low-privilege service account; ② set a protected branch on the DSL repo, require platform admin approval for merges (CODEOWNERS), and run the seed only from main. You can also place the seed job in a folder visible only to the platform team.
Verified teaching videos
No verified video was found that specifically demonstrates Job DSL seed jobs.
Official docs
- plugins.jenkins.io: Job DSL
- Job DSL Wiki (Tutorial, Script Security, Dynamic DSL)
- JCasC demos/jobs (pipeline.yaml, multibranch-github.yaml, gitea.yaml)
Video storyboard (about 80 seconds)
This courseware cannot directly generate video/MP3, but storyboards and narration scripts are provided.
Visual: jobs are copied manually in the UI; dozens of windows pile up, with colors gradually becoming inconsistent.
Narration: creating jobs by hand drifts as soon as the scale grows.
Visual: a “seed” falls into Jenkins and grows three job nodes: folder, multibranch, and nightly.
Narration: the seed job reads the DSL repo, generates jobs from code, and remembers what it generated.
Visual: a line is deleted from the DSL and the seed is run again; the corresponding job turns grey (DISABLE) or disappears (DELETE).
Narration: removedJobAction determines how jobs whose definitions were removed are handled. In production, disable first and observe one cycle before deleting.
Module 3 · Shared Libraries: reusing pipelines
- Master the library directory conventions:
vars/(global variables / custom steps),src/(Groovy classes),resources/(libraryResource) files read by the library). - Learn to use
@Library('lab-shared@v1.0') _,librarysteps, implicit loading, and understand defaultVersion / allowVersionOverride. - Understand the security implications of “globally trusted libraries are not subject to the sandbox”; distinguish global trusted libraries, global untrusted libraries, and folder-level libraries; learn to write unit tests for libraries.
What: what a Shared Library is
A Shared Library is an independent Git repository, stores pipeline code in a fixed directory structure, provided by the plugin Pipeline: Groovy Libraries (pipeline-groovy-lib, formerly workflow-cps-global-lib) is checked out at build time and loaded into the pipeline's Groovy classpath.
(root)
├── vars/
│ ├── myappPipeline.groovy # global variable: def call(Map cfg) { pipeline { … } }
│ ├── myappPipeline.txt # help text for this step (shown under Pipeline Syntax → Global Variables)
│ └── pytestStage.groovy # custom step: pytestStage()
├── src/
│ └── org/lab/Semver.groovy # plain Groovy class: import org.lab.Semver
└── resources/
└── org/lab/pod-python.yaml # read via libraryResource('org/lab/pod-python.yaml') (used in Module 5)
Why: why it is needed
- Change once, takes effect everywhere: cross-cutting logic such as security scanning, image signing, and notification formats is written only once.
- Versioning: the repo uses
v1.0,v1.1tags; critical services pin their versions, while other services followmain. - “Paved road”: business repos' Jenkinsfiles shrink to two or three lines, and the platform team is responsible for pipeline quality.
How: loading mechanism
- When the pipeline compiles the Jenkinsfile,
LibraryDecoratorfinds@Libraryannotation (or at runtime encounterslibrarystep). LibraryAdderit looks up a library config with the same name in turn across resolvers such as folder-level libraries,global untrusted libraries,global trusted libraries etc.; if none is found, it reportsCould not find any definition of libraries [...].- Version: if none is written
@versionuse defaultVersion; if one is written butallowVersionOverride=falsereportsVersion override not permitted for library …. - The retriever (usually Modern SCM → Git) checks that version out into the
libs/(caching can be enabled); if there is nosrcnorvarsit reportsLibrary … expected to contain at least one of src or vars directories. src/Added to the classpath;vars/*.groovyeach file in it becomes a global variable (the file name is the variable name,callmethod lets it be called like a step).- Trust level: code in global trusted libraries does not go through the Groovy sandbox; it can call any Java/Jenkins API, and can also use
@Grab; folder-level and global untrusted libraries run in the sandbox, and hitting an unapproved method throwsRejectedAccessException. - Library code, like the Jenkinsfile, follows the CPS rules (Lesson 2): it is interpreted on the controller,
shwhile steps are sent to the agent; classes must implementSerializable, and non-CPS methods use@NonCPS.
When: what belongs in the library
| Put in the library | Keep in the Jenkinsfile | Do not put in the library |
|---|---|---|
| Standard stages (test, build, scan, release), notifications, version calculation, Pod templates | Service-specific parameters (image name, port, deployment target) | Heavy business logic and complex computation (put it in shell/Python tools that run on the agent to lighten the controller's load) |
Comparison with similar technologies
| Jenkins Shared Library | GitHub Actions reusable workflows / composite actions | Azure Pipelines templates (extends/template) | |
|---|---|---|---|
| Language | Groovy (CPS) | YAML + actions in any language | YAML template expressions |
| Version reference | @Library('lib@v1.0') | uses: org/repo/.github/workflows/x.yml@v1 | resources.repositories + ref |
| Enforced use | Implicit loading (implicit) only makes the library “automatically available”; it cannot enforce use | Organization-level required workflows / rulesets | extends + required template checks |
For comparison:GitHub course 's reusable workflows,Azure DevOps course 's templates.
sh/bat steps' commands run on the agent. Writing large loops or parsing big JSON inside the library slows the controller. ② “Implicitly loaded libraries can force every pipeline to comply” — users can still choose not to call the steps in them. ③ “Making the library global trusted is more convenient” — this means anyone who can push to the library repo can execute arbitrary code with SYSTEM privileges, so the library repo must be protected to the same standard as Jenkins administrator access.Architecture diagram: business repos, library repo, and controller
Version strategy: who uses which version
Animation: how a build finds and loads lab-shared@v1.0
Step through the real processing order of pipeline-groovy-lib; switch between “trusted / untrusted” to see the difference in the last step.
Library code and invocation
| Syntax | Purpose | Notes |
|---|---|---|
@Library('lab-shared@v1.0') _ | Load at compile time | at the end is the _ is a placeholder for the annotation to attach to; multiple libraries can be loaded at once: @Library(['a', 'b@v2']) _ |
library 'lab-shared@main' | Dynamic load at runtime | a variable can decide the version; src/ classes are accessed through the return value |
libraryResource 'org/lab/pod-python.yaml' | Read a file in resources/ | Returns a string; commonly used for Pod templates and script templates |
| Pipeline Syntax → Global Variables Reference | View vars/*.txt help | Located on any pipeline job page |
| Replay | Temporarily modify the library code and re-run a build | For debugging; does not change the repo; requires the appropriate permissions |
// The entire Declarative Pipeline is defined in the library: the business repo only needs to call myappPipeline(...)
def call(Map cfg = [:]) {
String imageName = cfg.imageName ?: 'myapp'
pipeline {
agent none
options { buildDiscarder(logRotator(numToKeepStr: '20')) }
stages {
stage('Test') {
agent { docker { image 'python:3.13-slim'; label 'linux docker' } }
steps { pytestStage() }
}
stage('Build image') {
agent { label 'linux docker' }
steps {
script {
String tag = org.lab.Semver.buildTag(env.BRANCH_NAME ?: 'main', env.BUILD_NUMBER)
sh "docker build -t ${imageName}:${tag} ."
echo "built ${imageName}:${tag}"
}
}
}
}
}
}
def call(String requirements = 'requirements.txt') {
// Create a virtual environment in the workspace: the container runs as Jenkins' UID and cannot write to the system site-packages
sh """
python -m venv .venv
. .venv/bin/activate
pip install -q -r ${requirements} pytest
python -m pytest -q --junitxml=reports/junit.xml
"""
junit 'reports/junit.xml'
}
package org.lab
class Semver implements Serializable {
/** main branch: 1.1.<build>; other branches: 0.0.<build>-<branch> */
static String buildTag(String branch, String build) {
branch == 'main' ? "1.1.${build}" : "0.0.${build}-${branch.replaceAll('[^A-Za-z0-9]', '-')}"
}
}
@Library('lab-shared@v1.0') _
myappPipeline(imageName: 'myapp')
unclassified:
globalLibraries:
libraries:
- name: "lab-shared"
defaultVersion: "v1.0"
allowVersionOverride: true
implicit: false
includeInChangesets: false
retriever:
modernSCM:
scm:
git:
remote: "http://gitea:3000/lab/jenkins-shared-lib.git"
credentialsId: "gitea-myapp"
How to verify: The start of the build log shows Loading library lab-shared@v1.0, and the build page's left side has a version record for that library. Common errors: The library was changed but the build still uses old code — check whether a tag is pinned and whether library caching is enabled. Production use: defaultVersion points to the latest stable tag; validate in a few repos before moving it forward.
Lab 3: Publish lab-shared v1.0 and have myapp switch to it (about 8 minutes)
Environment: the Lesson 1 Jenkins (127.0.0.1:8080, which already has the Lesson 1–2 myapp pipeline job, Pipeline script from SCM, Script Path = Jenkinsfile) and Gitea.
GT=$(cat ~/jenkinslab/casc-lab/secrets/GITEA_TOKEN)
curl -s -X POST -H "Authorization: token $GT" -H 'Content-Type: application/json' \
http://127.0.0.1:3000/api/v1/user/repos -d '{"name":"jenkins-shared-lib","private":true,"default_branch":"main"}' | grep -o '"full_name":"[^"]*"'
mkdir -p ~/work/jenkins-shared-lib/{vars,src/org/lab,resources/org/lab} && cd ~/work/jenkins-shared-lib
# Save vars/myappPipeline.groovy, vars/pytestStage.groovy, and src/org/lab/Semver.groovy from the “Commands” tab to their paths
echo 'myappPipeline(imageName: String): standard pipeline for myapp (test + build image)' > vars/myappPipeline.txt
git init -b main && git add . && git commit -m "lab-shared v1.0"
git tag v1.0
git push "http://lab:$GT@127.0.0.1:3000/lab/jenkins-shared-lib.git" main v1.0
"full_name":"lab/jenkins-shared-lib" * [new branch] main -> main * [new tag] v1.0 -> v1.0
lab-shared, Default version v1.0, check Allow default version to be overridden, Retrieval method: Modern SCM → Git, Project Repository http://gitea:3000/lab/jenkins-shared-lib.git, Credentials gitea-myapp → Save. (For the JCasC equivalent, see the “Commands” tab; Module 4 puts it into the Helm values.)cd ~/work/myapp # lab/myapp cloned in Lesson 2
cp Jenkinsfile Jenkinsfile.hour2.bak
printf "@Library('lab-shared@v1.0') _\nmyappPipeline(imageName: 'myapp')\n" > Jenkinsfile
git add Jenkinsfile && git commit -m "ci: use lab-shared v1.0" && git push origin mainmyapp click Build Now; if webhooks/polling were configured in Lesson 2, it triggers automatically):
Loading library lab-shared@v1.0 Attempting to resolve v1.0 from remote references... > git ls-remote -h -t -- http://gitea:3000/lab/jenkins-shared-lib.git # timeout=10 Found match: refs/tags/v1.0 revision 3f1c2a… ... [Pipeline] stage (Test) + python -m pytest -q --junitxml=reports/junit.xml 4 passed in 0.41s [Pipeline] stage (Build image) + docker build -t myapp:1.1.12 . built myapp:1.1.12 Finished: SUCCESS
Semver.buildTag (for example, change it to 1.2. prefix) and push, but do not tag. When myapp builds again, it still gets 1.1.N (pinned to v1.0). Then on the most recent build page, click Replay, change the Jenkinsfile annotation to @Library('lab-shared@main') _ and re-run; this time you get 1.2.N, using the unreleased new code — this is the practice of “validate library changes in a few repos/builds first, then tag and publish.” (In a multibranch job, each branch's BRANCH_NAME differs,Semver will generate 0.0.N-branch-name.)vars/pytestStage.groovy contents and re-run once, without affecting the repo.git mv -f Jenkinsfile.hour2.bak Jenkinsfile && git commit -m revert && git push. Later modules keep the library version by default.vars/ and src/ (mock sh,junit etc. steps); the library repo's own CI should run these tests, and in the integration build use library "lab-shared@${env.BRANCH_NAME}" (the at-runtime library step can take variables, annotations cannot) to load the branch under test.Case 1: unified image signing and SBOM
Problem: The security team requires all images to generate an SBOM and be signed, affecting 120 repositories. Approach: Add to the library vars/publishImage.groovy a step that wraps build → SBOM → sign → push; publish v2.0, and move defaultVersion forward in three batches (10 → 50 → all), watching the failure rate for each batch. Limits: Repos pinned to an old version do not automatically get the new step; deprecation warnings need to be output from the library (unstable or echo), and usage per version should be tracked regularly.
Case 2: library code saturates controller CPU
Problem: The library parses tens of MB of test-report JSON in Groovy and loops over calculations; controller CPU hits 100% and all builds slow down. Approach: Move the parsing logic to a Python script running on the agent (sh 'python tools/summarize.py'); the library only reads the condensed results; large @NonCPS methods also occupy controller threads and should be avoided where possible. Limits: Problems like this often only surface as scale grows; Lesson 7 covers how to locate them with thread dumps.
Case 3: library repo used as a privilege-escalation channel
Problem: An audit found that developers could push directly to main of the global trusted library, and defaultVersion was main. Approach: Enable protected branches and required approvals on the library repo; change defaultVersion to a tag; move team-private tools to a folder-level library (runs in the sandbox). Limits: A library in the sandbox that hits an unapproved method needs administrator approval (Lesson 6, Script Security).
Common errors and fixes
Could not find any definition of libraries [lab-shared@v1.0]
Cause: The library name is spelled differently; the library config is in another folder; or the config is on the 8082 instance while the build runs on the 8080 instance.
Fix: Check the library name in Manage Jenkins → System, or the Pipeline Libraries config of the job's folder.
No version v9 found for library lab-shared
Cause: The tag/branch does not exist, or the tag was not pushed (git push tags are not pushed by default).
git ls-remote --tags http://127.0.0.1:3000/lab/jenkins-shared-lib.git
Fix:git push origin v1.0.
Library lab-shared expected to contain at least one of src or vars directories
Cause: Library contents are placed in a subdirectory (such as jenkins/vars/), or an empty branch was checked out.
Fix: Move vars/,src/ to the repository root; or set “Library Path” in the retriever (only relative paths are supported; must not contain ..).
java.lang.NoSuchMethodError: No such DSL method 'myappPipeline' found among steps [...]
Cause: The library was not loaded (forgot @Library and the library does not set implicit), or the file name does not match the call name (vars/myappPipeline.groovy case-sensitive).
Fix: Add the annotation or enable implicit; check the file name.
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use staticMethod jenkins.model.Jenkins get
Cause: A folder-level or global untrusted library runs in the sandbox and called an unapproved internal API.
Fix: Preferably rewrite it as an implementation that does not need internal APIs; if truly needed, have an administrator approve it, or move this code into a trusted library (and protect that library at administrator level).
java.io.NotSerializableException: org.lab.SomeHelper
Cause: A class instance in the library is still referenced across CPS persistence points (between steps), but does not implement Serializable (the mechanism covered in Lesson 2).
Fix: Have the class implement Serializable; limit non-serializable objects to @NonCPS local variables within a method.
1. Write the annotations to load the main branch of lab-shared and the v2 tag of the tools library.
@Library(['lab-shared@main', 'tools@v2']) _
2. In a library step, read resources/org/lab/pod-python.yaml and print the line count.
def podYaml = libraryResource 'org/lab/pod-python.yaml'
echo "pod template has ${podYaml.readLines().size()} lines"After the new library version v1.2 is released, 30% of repo builds fail. How do you stop the bleeding within 5 minutes, and how do you prevent it next time?
Stop the bleeding: change the global library's defaultVersion back to v1.1 (edit in JCasC and reload, or edit in the UI); handle repos pinned to v1.2 separately. Prevention: the library repo's own CI runs JenkinsPipelineUnit tests plus integration builds of a few representative repos; move defaultVersion forward in batches; keep the library backward compatible (new parameters get default values), and publish breaking changes under a new major version with an announcement.
Verified teaching videos
No video verified via oEmbed that specifically covers Shared Libraries was found.
Official docs
- Jenkins Handbook: Extending with Shared Libraries
- plugins.jenkins.io: Pipeline: Groovy Libraries
- JenkinsPipelineUnit
Video storyboard (about 90 seconds)
This courseware cannot directly generate video/MP3, but storyboards and narration scripts are provided.
Visual: 30 nearly identical Jenkinsfiles laid out side by side, with the differences flashing red.
Narration: copy-pasted pipelines fork sooner or later.
Visual: the library repo's three directories vars, src, resources expand in turn; the business repo's Jenkinsfile shrinks to two lines.
Narration: put common logic into a shared library; the business repo writes just one line of invocation.
Visual: tags v1.0 and v1.1 lined up along a timeline; arrows from different services point to different tags.
Narration: publish library versions with Git tags, lock critical services, and move the default version forward in batches.
Visual: a shield icon on “global trusted library” turns into a key.
Narration: the global trusted library bypasses the sandbox. Anyone who can push to it is effectively a Jenkins administrator.
Module 4 · Running Jenkins on Kubernetes with Helm
- Use
helm upgrade --install jenkins jenkins/jenkins -n jenkins -f values-lab.yamlto deploy the controller, and read the generated StatefulSetjenkins, Servicejenkins/jenkins-agent, PVC, ServiceAccount, and Role. - Understand the chart's three configuration channels:
installPlugins/additionalPlugins(init containerinitinstalls plugins),JCasC.configScripts(ConfigMap +config-reloadsidecar hot reload),additionalExistingSecrets(Kubernetes Secret →${secret-key}). - Migrate the Module 1–3 YAML, seed jobs, and shared library into values, producing a Jenkins that can be rebuilt after deletion.
What: the jenkins chart in jenkinsci/helm-charts
This is the official chart maintained by the Jenkins community (repository https://charts.jenkins.io, OCI: oci://ghcr.io/jenkinsci/helm-charts/jenkins. As of 2026-11-16 the latest is 5.13.3, appVersion 2.580.2, default image docker.io/jenkins/jenkins:2.580.2-jdk25, installs the plugins kubernetes / workflow-aggregator / git / configuration-as-code by default, and configures a Kubernetes cloud by default using JCasC (name kubernetes).
| Generated resources (release = jenkins) | Purpose |
|---|---|
StatefulSet jenkins (replicas can only be 1 or 0) | controller Pod jenkins-0: init container config-reload-init,init, main container jenkins, sidecar config-reload |
PVC jenkins (default 8Gi, RWO) | JENKINS_HOME (/var/jenkins_home) |
Service jenkins (8080),jenkins-agent (50000) | UI/HTTP and inbound agent TCP ports |
ConfigMap jenkins,jenkins-jenkins-config-* | plugin list and apply_config.sh; one ConfigMap per JCasC configScript |
Secret jenkins (or existingSecret) | administrator username/password, mounted to /run/secrets/additional/ |
ServiceAccount jenkins + Role/RoleBinding | lets the Kubernetes plugin create/delete agent Pods in the namespace; config-reload reads the ConfigMap |
Why: why run the controller on Kubernetes
- The controller is guarded by a StatefulSet; after a node failure it is rebuilt on another node (data is on the PVC).
- Works naturally with the dynamic Pod agents of Module 5: controller and agents are in the same cluster and connect via Service DNS.
- All configuration lives in values: plugin versions, JCasC, resources, probes, network policies, ServiceMonitor (Module 7).
How: the three configuration channels
- Plugins:
controller.installPlugins+additionalPluginswritten to the list in the ConfigMapplugins.txt; the init containerinitrunsapply_config.sh, callingjenkins-plugin-clito download plugins. Changing the plugin list changes the Pod template'schecksum/configannotation → the StatefulSet rolling-restarts the controller. - JCasC: the chart ships a default configuration (security realm, authorization, Kubernetes cloud,
locationetc.); yourcontroller.JCasC.configScripts.<name>each entry generates a labeled ConfigMap.config-reloadThe sidecar (kiwigrid/k8s-sidecar 2.14.3) watches these ConfigMaps, writes into/var/jenkins_home/casc_configs/, then callshttp://localhost:8080/reload-configuration-as-code/?casc-reload-token=$(POD_NAME)——without restarting the Pod. - Secrets:
controller.additionalExistingSecretsMount a key from an existing Secret, and reference it in JCasC as${<secret name>-<key name>}; the administrator account usescontroller.admin.existingSecret.
When: trade-offs in production
- Plugins: OK for labs
installPlugins; production recommends a custom-built image (Dockerfile +jenkins-plugin-cli) and setinstallPlugins: false, so startup does not depend on the update center, images can be scanned, and rollback only requires switching the tag.controller.initializeOnce: trueThis avoids re-downloading plugins on every restart. - Single replica: the Jenkins controller does not support multi-replica active/standby; the chart limits
replicas≤ 1; high availability relies on fast rebuild + backups (Module 6) or splitting into multiple controllers. - Ingress: this lesson uses
kubectl port-forward; production can usecontroller.ingressor the chart's newly addedcontroller.httpRoute(Gateway API).
Comparison with other deployment methods
| Helm chart (this lesson) | Docker Compose (Lesson 1) | Jenkins Operator | CloudBees CI (commercial) | |
|---|---|---|---|---|
| Configuration | values + JCasC | compose.yaml + manual / JCasC | CRD | CasC bundles + operations center |
| agent | Kubernetes plugin Pods | fixed-container agent1 | Pod | Pods, centrally managed |
| Suited for | most self-hosted teams | single machine / lab | Depends on project status; check its repository activity before choosing | large scale, needs vendor support |
configScripts changes, the sidecar hot-reloads; only changing plugins, the image, or JVM parameters causes a rolling restart. ② “helm uninstall does not touch JENKINS_HOME” — in chart 5.13.3 the PVC is a regular template resource (not volumeClaimTemplates, and there is no helm.sh/resource-policy: keep),uninstall deletes the PVC; kind's local-path reclaim policy is Delete, so the data disappears with it. To keep it, use persistence.annotations plus helm.sh/resource-policy: keep or use persistence.existingClaim, and back up before uninstalling (Module 6). ③ “Setting the Jenkins URL in configScripts” — the chart's default configuration already declares location, which causes a conflict; use controller.jenkinsUrl.Architecture diagram: the composition of release jenkins in namespace jenkins
Flowchart: two different paths for taking effect after helm upgrade
helm diff or helm template to determine which path a change belongs to; when a restart is needed, enter quiet-down mode firstAnimation: after helm upgrade --install, how resources become ready in order
Each step corresponds to what you can observe with kubectl get events -n jenkins -w or kubectl logs real events. The last step demonstrates the hot-reload path when only JCasC is changed.
Core commands
| Command | Purpose | Key parameters |
|---|---|---|
helm show values jenkins/jenkins --version 5.13.3 | View all configurable items (about 1500 lines) | read together with the parameter table in the README |
helm upgrade --install jenkins jenkins/jenkins -n jenkins -f values-lab.yaml --version 5.13.3 | Install or upgrade | pin --version; for Helm 4's wait behavior, see the Helm course |
helm template … | less / helm diff upgrade … | Preview rendered result / diff (helm-diff plugin) | determine whether the controller will restart |
kubectl -n jenkins port-forward svc/jenkins 8081:8080 | Access the UI locally | 8080 is already used by the Lesson 1 Compose instance, so use 8081 |
kubectl -n jenkins logs jenkins-0 -c init / -c config-reload | Plugin install log / hot-reload log | Preferred for troubleshooting |
helm rollback jenkins <REV> -n jenkins | Roll back the release | Rolls back only the K8s objects; upgraded plugins/data in JENKINS_HOME are not automatically reverted |
controller:
image:
tag: "2.580.2-jdk21" # matches Lesson 1; the chart default is 2.580.2-jdk25
numExecutors: 0
jenkinsUrl: "http://127.0.0.1:8081/"
admin:
existingSecret: jenkins-admin # keys: jenkins-admin-user / jenkins-admin-password
resources:
requests: { cpu: "500m", memory: "1Gi" }
limits: { memory: "2Gi" }
javaOpts: "-XX:MaxRAMPercentage=70"
installPlugins: # the 4 plugins the chart 5.13.3 installs by default
- kubernetes:4560.vc25b_83890c34
- workflow-aggregator:608.v67378e9d3db_1
- git:5.11.0
- configuration-as-code:2147.v8a_8d38668c72
additionalPlugins:
- job-dsl:3732.v9a_c49a_61a_313
- pipeline-groovy-lib:822.vc95f70dea_db_7
- matrix-auth:3.3
- gitea:286.v0740a_413c1eb_
- junit:1458.1460.vd53b_087eeb_2c # LTS-compatible version; the latest requires 2.589 (weekly)
additionalExistingSecrets:
- name: jenkins-casc-secrets
keyName: gitea-token # referenced in JCasC as ${jenkins-casc-secrets-gitea-token}
JCasC:
authorizationStrategy: |-
globalMatrix:
entries:
- user:
name: "admin"
permissions:
- "Overall/Administer"
- group:
name: "authenticated"
permissions:
- "Overall/Read"
- "Job/Read"
- "Job/Build"
configScripts:
system: |
jenkins:
systemMessage: "kind lab · Helm release jenkins · managed by JCasC in values-lab.yaml"
credentials: |
credentials:
system:
domainCredentials:
- credentials:
- usernamePassword:
scope: GLOBAL
id: "gitea-myapp"
username: "lab"
password: "${jenkins-casc-secrets-gitea-token}"
libraries: |
unclassified:
globalLibraries:
libraries:
- name: "lab-shared"
defaultVersion: "v1.0"
allowVersionOverride: true
retriever:
modernSCM:
scm:
git:
remote: "http://gitea:3000/lab/jenkins-shared-lib.git"
credentialsId: "gitea-myapp"
jobs: |
security:
globalJobDslSecurityConfiguration:
useScriptSecurity: false
jobs:
- script: >
folder('platform')
- script: >
pipelineJob('platform/seed') {
definition {
cpsScm {
scm { git { remote { url('http://gitea:3000/lab/jenkins-jobs.git'); credentials('gitea-myapp') }; branch('*/main') } }
scriptPath('Jenkinsfile')
}
}
}
persistence:
enabled: true
size: 8Gi
agent:
enabled: true # covered in detail in Module 5
podRetention: "Never"
How to verify:helm template jenkins jenkins/jenkins --version 5.13.3 -f values-lab.yaml | grep -c 'kind: ConfigMap' You can see the ConfigMap generated for each configScript. Common errors: configScripts keys may only contain lowercase letters, digits, and hyphens (RFC 1123); values must start with a JCasC root element. Production use: Split into multiple values files by team/domain (the chart README recommends -f values_main.yaml -f values_casc.yaml).
Lab 4: Deploy release jenkins in the kind cluster lab (about 7 minutes + waiting for the first image and plugin pulls)
cd ~/jenkinslab/k8s kubectl -n jenkins create secret generic jenkins-admin \ --from-literal=jenkins-admin-user=admin \ --from-literal=jenkins-admin-password="$(openssl rand -base64 18)" kubectl -n jenkins create secret generic jenkins-casc-secrets \ --from-file=gitea-token=$HOME/jenkinslab/casc-lab/secrets/GITEA_TOKEN
secret/jenkins-admin created secret/jenkins-casc-secrets created
values-lab.yaml from the “Commands” tab, save to ~/jenkinslab/k8s/:
helm template jenkins jenkins/jenkins -n jenkins --version 5.13.3 -f values-lab.yaml \ | grep -E '^kind:|^ name:' | paste - - | sort | uniq
kind: ConfigMap name: jenkins kind: ConfigMap name: jenkins-jenkins-config-authorizationstrategy kind: ConfigMap name: jenkins-jenkins-config-credentials kind: ConfigMap name: jenkins-jenkins-config-jobs kind: ConfigMap name: jenkins-jenkins-config-libraries kind: ConfigMap name: jenkins-jenkins-config-securityrealm kind: ConfigMap name: jenkins-jenkins-config-system kind: ConfigMap name: jenkins-jenkins-jcasc-config kind: PersistentVolumeClaim name: jenkins kind: Role name: jenkins-schedule-agents kind: Service name: jenkins kind: Service name: jenkins-agent kind: ServiceAccount name: jenkins kind: StatefulSet name: jenkins ...
Use the exact names of the ConfigMap / Role from your rendered output.
helm upgrade --install jenkins jenkins/jenkins -n jenkins --version 5.13.3 -f values-lab.yaml kubectl -n jenkins get pod jenkins-0 -w # watch Init:0/2 → Init:1/2 → PodInitializing → Running 2/2
Release "jenkins" does not exist. Installing it now. NAME: jenkins NAMESPACE: jenkins STATUS: deployed REVISION: 1 ... NAME READY STATUS RESTARTS AGE jenkins-0 0/2 Init:1/2 0 25s jenkins-0 0/2 PodInitializing 0 2m10s jenkins-0 1/2 Running 0 2m14s jenkins-0 2/2 Running 0 3m02s
kubectl -n jenkins logs jenkins-0 -c init | tail -5 kubectl -n jenkins logs jenkins-0 -c jenkins | grep -E 'fully up and running|casc|SEVERE' | head kubectl -n jenkins exec jenkins-0 -c jenkins -- ls /var/jenkins_home/casc_configs
Done ... INFO hudson.lifecycle.Lifecycle#onReady: Jenkins is fully up and running authorizationstrategy.yaml credentials.yaml jcasc-default-config.yaml jobs.yaml libraries.yaml securityrealm.yaml system.yaml
kubectl -n jenkins port-forward svc/jenkins 8081:8080 >/dev/null 2>&1 &
PW=$(kubectl -n jenkins get secret jenkins-admin -o jsonpath='{.data.jenkins-admin-password}' | base64 -d)
curl -s -u "admin:$PW" 'http://127.0.0.1:8081/api/json?tree=description,jobs[name]'
curl -s -u "admin:$PW" 'http://127.0.0.1:8081/credentials/store/system/domain/_/api/json?tree=credentials[id]'
{"_class":"hudson.model.Hudson","description":"kind lab · Helm release jenkins · managed by JCasC in values-lab.yaml","jobs":[{"_class":"com.cloudbees.hudson.plugins.folder.Folder","name":"platform"}]}
{"_class":"com.cloudbees.plugins.credentials.CredentialsStoreAction$DomainWrapper","credentials":[{"id":"gitea-myapp"}]}system the systemMessage, then run the same helm upgrade:
sed -i 's/managed by JCasC in values-lab.yaml/hot-reloaded v2/' values-lab.yaml
helm upgrade --install jenkins jenkins/jenkins -n jenkins --version 5.13.3 -f values-lab.yaml
kubectl -n jenkins logs jenkins-0 -c config-reload --since=2m | grep -iE 'reload|Writing|Contents' | tail -3
kubectl -n jenkins get pod jenkins-0 -o jsonpath='{.status.containerStatuses[?(@.name=="jenkins")].restartCount}{"\n"}'
... Writing /var/jenkins_home/casc_configs/system.yaml ... ... Contents of system.yaml changed, sending request to http://localhost:8080/reload-configuration-as-code/?casc-reload-token=jenkins-0 ... 0
It takes a few seconds to a minute for the ConfigMap update to reach the sidecar; restartCount stays at 0. The exact sidecar log format varies by version.
platform/seed It needs an agent to run — this is exactly the problem Module 5 solves. Triggering it now keeps it queued, showing ‘Jenkins’ doesn’t have label ‘linux’.useScriptSecurity: false prerequisites are in Module 2. Later modules in this lesson and Lessons 6 and 7 continue to use this release,so do not uninstall; for full cleanup see Module 8.Case 1: managing Jenkins itself with GitOps
Problem: Values files are scattered across personal computers, and there is no way to trace who upgraded a plugin. Approach: Put values and JCasC into platform/jenkins-config a repository, sync the Helm release with Argo CD / Flux; for secrets, use External Secrets Operator to sync from Key Vault/Secrets Manager into jenkins-casc-secrets. Limits: Both the GitOps controller and the config-reload sidecar “correct drift”; make sure manual UI changes are prohibited (authorization strategy + System Message).
Case 2: the controller takes 10 minutes on every restart
Problem: Every time the Pod is rebuilt,init the container downloads 120 plugins from the update center, and occasionally fails due to network errors. Approach: Build a custom image registry.example.com/jenkins:2.580.2-jdk21-p20261116 (running in the Dockerfile jenkins-plugin-cli), and in values set installPlugins: false; the image is scanned in CI and validated in staging. Limits: Every plugin update requires rebuilding the image, so an automated pipeline is needed (Renovate/Dependabot updating plugins.txt).
Case 3: controller gets OOMKilled
Problem: When many pipelines run concurrently, the controller gets OOMKilled and all builds are interrupted. Approach: Set resources.requests.memory = limits.memory, and the JVM uses -XX:MaxRAMPercentage=70 to leave headroom for non-heap memory; move heavy computation to agents; monitor heap usage and GC per Module 7. Limits: The JVM heap is not the only memory consumer (metaspace, thread stacks, direct memory); load testing is needed to determine the values.
Common errors and fixes
jenkins-0 stuck at Init:1/2; init container log: Unable to resolve plugin URL … / Plugin X depends on Y:… but there is an older version installed / requires a greater version of Jenkins
Cause: Cannot reach the update center; or the plugin version requires a Jenkins core higher than the current image (for example, the latest junit requires 2.589, while the LTS is 2.580.2).
kubectl -n jenkins logs jenkins-0 -c init | tail -30
Fix: Choose plugin versions compatible with the LTS (look up https://updates.jenkins.io/update-center.actual.json?version=2.580.2); in production, switch to a custom image with pre-installed plugins.
PVC jenkins stays Pending: waiting for first consumer to be created before binding
Cause: kind's local-path StorageClass uses WaitForFirstConsumer, so the PVC is naturally Pending until the Pod is scheduled; if the Pod is also Pending, check the Pod events.
kubectl -n jenkins describe pvc jenkins | tail -5 kubectl -n jenkins describe pod jenkins-0 | tail -15
Fix: Usually waiting is enough; if node resources are insufficient (Insufficient memory), lower the requests or add kind nodes.
Error: INSTALLATION FAILED: cannot re-use a name that is still in use
Cause: A release with the same name already exists (possibly a failed install).
helm list -n jenkins -a
Fix: Always use helm upgrade --install; when in failed state, fix the values and upgrade again or roll back.
Found conflicting configuration at YamlSource: /var/jenkins_home/casc_configs/system.yaml
Cause: Keys that the chart's default configuration already has were declared again in configScripts (common ones: unclassified.location,jenkins.clouds,securityRealm).
kubectl -n jenkins exec jenkins-0 -c jenkins -- cat /var/jenkins_home/casc_configs/jcasc-default-config.yaml | head -60
Fix: Use the dedicated values provided by the chart (controller.jenkinsUrl,controller.JCasC.securityRealm,agent.*); or set controller.JCasC.defaultConfig: false and write everything yourself (you must also declare the cloud yourself).
config-reload log: Connection refused / 409 Conflict
Cause: The sidecar triggers a reload before Jenkins has finished starting (it retries,reqRetryConnect default 10); or a reload is already in progress (409; JCasC allows only one reload at a time).
Fix: It usually recovers automatically; if it keeps failing, manually run Manage Jenkins → Configuration as Code → Reload, and check the YAML for errors.
1. Retrieve the user values and chart version currently in effect for release jenkins.
helm get values jenkins -n jenkins helm list -n jenkins -o json | python3 -c 'import json,sys;[print(r["name"], r["chart"], r["app_version"]) for r in json.load(sys.stdin)]'
2. Without using the UI, confirm that the job-dsl plugin and its version are loaded in the controller.
curl -s -u "admin:$PW" 'http://127.0.0.1:8081/pluginManager/api/json?depth=1&tree=plugins[shortName,version]' \ | python3 -c 'import json,sys;[print(p["shortName"],p["version"]) for p in json.load(sys.stdin)["plugins"] if p["shortName"]=="job-dsl"]'
The team requires “changing plugin versions must not interrupt builds during working hours”, but JCasC changes can be made at any time. Design the release process.
Split changes into two categories: configScripts changes go through hot reload and can be merged at any time; plugin/image/JVM changes are released in a maintenance window: first validate in a staging release, and before release run in the UI or CLI quiet-down (wait for running builds to finish and stop accepting new builds), then helm upgrade, and after confirming, cancel-quiet-down. In CI, use helm-diff to automatically determine whether a change touches the Pod template, and label the PR “needs maintenance window”.
Teaching videos
No video verified via YouTube oEmbed that specifically covers the jenkinsci Helm chart was found. For Helm itself, see the Helm course video page. The verified video below demonstrates Pod agents on Kubernetes and can be watched together with Module 5:
Official docs
- jenkinsci/helm-charts: charts/jenkins (README, VALUES.md, values.yaml)
- Jenkins Handbook: Installing Jenkins on Kubernetes
- chart releases (jenkins-5.13.3, 2026-11-15)
Video storyboard (about 90 seconds)
This courseware cannot directly generate video/MP3, but storyboards and narration scripts are provided.
Visual: one values file split into three colored blocks: plugins, JCasC, secrets.
Narration: the official Helm chart splits Jenkins configuration into three channels.
Visual: inside Pod jenkins-0, two init containers light up in turn, then the main container and the config-reload sidecar run side by side.
Narration: init containers install plugins first; when the main container starts, JCasC reads the configuration; the sidecar handles hot reloads afterwards.
Visual: after changing systemMessage and running helm upgrade, the ConfigMap flashes, the sidecar sends a POST, and the Pod restart count stays at 0.
Narration: when only configuration changes, Jenkins does not need to restart.
Visual: changing the plugin version; the StatefulSet deletes and recreates the Pod.
Narration: changing plugins or the image triggers a rolling restart of the controller; schedule a maintenance window and enter quiet-down mode first.
Module 5 · Kubernetes plugin: dynamic Pod agents
- Step by step, explain the full mechanism of a build from queuing to Pod deletion: queue → NodeProvisioner → KubernetesCloud → Kubernetes API creates Pod → scheduling/kubelet → inbound agent connects back → executor →
containersteps run via the exec API → delete the Pod. - Be proficient in writing
agent { kubernetes { yaml … ; defaultContainer … } }and scriptedpodTemplate/POD_LABEL, and understand the jnlp container, shared workspace, and multi-container Pods. - Be able to configure cloud-level and template-level parameters: containerCap, instanceCap, idleMinutes, podRetention, resource requests, ServiceAccount, connection method (TCP 50000 / WebSocket).
What: what the Kubernetes plugin does
The Kubernetes plugin implements Jenkins' Cloud extension point: when a job in the queue needs a certain label and no executor is free, it, based on Pod Template calls the Kubernetes API to create a Pod as a one-time agent. Each Pod always has one jnlp container running Jenkins remoting (image jenkins/inbound-agent), which connects actively to the controller; other containers (such as python,redis) work together through a shared workspace volume (/home/jenkins/agent). It is only responsible for the agent, does not install the controller, and does not create the cluster.
Why: why use Pod agents
- Clean: each build gets a fresh environment, with no leftover dependencies or cache pollution from previous builds;
- Elastic: consumes no resources when there are no builds; at peak, it scales within the limits of Kubernetes capacity and
containerCaplimits; - Declarative toolchain: Pod YAML lives in the repo alongside the Jenkinsfile, and different projects use different images (python:3.13-slim, node, golang), so there is no need to maintain a “one-size-fits-all agent”;
- Isolation: different teams can use different namespaces, ServiceAccounts, NetworkPolicies, and ResourceQuotas.
How: full mechanism
- Queue: the Declarative
agent { kubernetes {…} }generates a temporary Pod Template and a unique label for this build; the queue item shows “Waiting for next available executor on ‘…’”. - Provisioning decision: Jenkins' NodeProvisioner asks each Cloud whether it can provide the label; the Kubernetes plugin has a provisioning strategy that does not wait for load statistics and can trigger creation immediately (can be turned off with a system property).
- Create Pod: the plugin registers a node in Jenkins
KubernetesSlavenode (offline), merges the template (inheritsinheritFrom, YAML merge strategy), and automatically injectsjnlpcontainer and environment variables (JENKINS_URL,JENKINS_SECRET,JENKINS_AGENT_NAME,JENKINS_TUNNELetc.), and uses the ServiceAccount token to send a request to kube-apiserver toPOST /api/v1/namespaces/jenkins/pods. - Scheduling and startup: kube-scheduler binds the node, kubelet pulls the image and starts the containers; the plugin watches Pod status, and if it exceeds
waitForPodSec(chart default 600 seconds) without becoming ready, it gives up and logs the reason. - Connect back: the remoting in the jnlp container uses the secret to connect to the controller — via TCP, connecting to
jenkins-agent.jenkins.svc.cluster.local:50000(chart default), or via WebSocket over HTTP 8080. After a successful handshake, the node goes online. - Execute: the queue assigns the build to an executor on that node.
container('python')(ordefaultContainer) steps inside theshis not SSH; instead the plugin uses the Kubernetes exec API (pods/exec) to start a process in the target container, and output streams back to the console via jnlp/controller. - Cleanup: when the build ends, the executor is released;
podRetention: Never(default), the plugin deletes the Pod and removes the node.idleMinutes> 0 lets the Pod stay idle for a while for reuse (at the cost of isolation).
When: when to use and when not to use
| Scenario | Recommendation |
|---|---|
| Testing and building for Python/Node/Go/Java | Ideal; for dependency caching use a PVC (persistentVolumeClaim volume) or an artifact repository proxy |
| Building container images inside a Pod | Avoid mounting the host Docker socket or privileged containers; options include rootless BuildKit, remote build services, etc. (check each project's current status for specific tools) |
| Builds that need GPU/Windows/macOS | GPU and Windows nodes can be targeted via nodeSelector/tolerations; macOS can only use static agents |
| Extremely short tasks (a few seconds) in very large volume | Pod startup overhead (image pull, scheduling, connect-back) may exceed the task itself; pre-pull images or consider idleMinutes |
Comparison with similar technologies
| Kubernetes plugin Pod agent | Static agent (Lesson 1 agent1) | GitHub Actions ARC / Azure Pipelines self-hosted agent on K8s | |
|---|---|---|---|
| Lifecycle | Created per build, deleted when finished | Long-running | ARC: runner Pods scale on demand |
| Toolchain | each pipeline chooses its own image | pre-installed on the agent | runner image + container jobs |
| State pollution | None | Yes (requires regular cleanup) | Depends on configuration |
sh is entering other containers from the jnlp container via SSH” — it is the Kubernetes exec API, which requires pods/exec . ② “Containers in the Pod keep running until the build ends” — tool containers need a long-running command (such as sleep infinity), otherwise the container exits right after starting and the Pod fails. ③ “containerCap is a cluster-wide limit” — it only limits the number of agent Pods this Cloud can have at the same time; the real resource ceiling comes from the namespace ResourceQuota and node capacity. ④ “Agent Pods must connect on port 50000” — WebSocket mode only needs the HTTP(S) port, which suits strict network policies or cross-cluster scenarios.Architecture diagram: controller, Cloud, and agent Pod
Sequence diagram: Pod agent lifecycle for one build
Core animation: the Kubernetes plugin creates a Pod agent for a queued build
Choose “Fault injection” to see at which step common failures occur and what the logs look like. The terminal content corresponds to the build console,kubectl get pods -w and the lines you would actually see in events.
Pipeline syntax and parameters
| Syntax / parameter | Purpose | Notes |
|---|---|---|
agent { kubernetes { yaml '''…'''; defaultContainer 'python' } } | Declarative: generate Pod for this pipeline | Also can yamlFile 'ci/pod.yaml' (read from the repo),inheritFrom 'default' |
podTemplate(yaml: …) { node(POD_LABEL) { container('python') { … } } } | Scripted: define the template explicitly | POD_LABEL is the unique label generated by the plugin |
container('name') { sh … } | run steps in a specified container | If unspecified, runs in the jnlp container (or defaultContainer) |
cloud: containerCapStr | maximum number of agent Pods this Cloud can have at the same time | chart value agent.containerCap (default 10) |
templates: instanceCap,idleMinutes,podRetention | per-template limit / idle retention / whether to keep the Pod after failure | For debugging, you can temporarily set podRetention: onFailure |
chart: agent.websocket,agent.directConnection | connection method | default TCP (jenkinsTunnel = jenkins-agent:50000) |
showRawYaml | whether to print the Pod YAML in the console | consider turning it off if environment variables are included (chart value agent.showRawYaml) |
pipeline {
agent {
kubernetes {
yaml '''
apiVersion: v1
kind: Pod
metadata:
labels:
app.kubernetes.io/part-of: myapp-ci
spec:
containers:
- name: python
image: python:3.13-slim
command: ["sleep"]
args: ["infinity"]
resources:
requests: { cpu: "250m", memory: "256Mi" }
limits: { memory: "512Mi" }
'''
defaultContainer 'python'
}
}
options { timeout(time: 15, unit: 'MINUTES') }
stages {
stage('Test') {
steps {
sh '''
python -m venv .venv && . .venv/bin/activate
pip install -q -r requirements.txt pytest
python -m pytest -q --junitxml=reports/junit.xml
'''
}
post { always { junit 'reports/junit.xml' } }
}
stage('Where am I') {
steps {
container('jnlp') { sh 'echo "agent=$NODE_NAME pod=$(hostname)"; java -version 2>&1 | head -1' }
}
}
}
}
Created Pod: kubernetes jenkins/myapp-k8s-pytest-3-qwt6v-x1z2c Agent myapp-k8s-pytest-3-qwt6v-x1z2c is provisioned from template myapp_k8s-pytest_3-qwt6v --- apiVersion: "v1" kind: "Pod" ... Running on myapp-k8s-pytest-3-qwt6v-x1z2c in /home/jenkins/agent/workspace/myapp/k8s-pytest [Pipeline] sh + python -m pytest -q --junitxml=reports/junit.xml 4 passed in 0.39s ... agent=myapp-k8s-pytest-3-qwt6v-x1z2c pod=myapp-k8s-pytest-3-qwt6v-x1z2c Finished: SUCCESS
def call(Closure body) {
podTemplate(yaml: libraryResource('org/lab/pod-python.yaml')) {
node(POD_LABEL) {
checkout scm
container('python') { body() }
}
}
}
// In the Jenkinsfile: @Library('lab-shared@v1.1') _ k8sPython { sh 'python -m pytest -q' }
# watch agent Pods being created and deleted (open another terminal) kubectl -n jenkins get pods -w # view the plugin's records in the controller log kubectl -n jenkins logs jenkins-0 -c jenkins | grep -E 'KubernetesCloud|KubernetesLauncher|Created Pod' | tail -5
How to verify:get pods -w you can see the Pod go from Pending → Running → Terminating. Common errors: The tool container has no long-running command, causing Completed/CrashLoopBackOff; requests that are too large cause Pending. Production use: Put the Pod YAML in the shared library resources or yamlFile, to unify resource requests and the security context.
Lab 5: myapp's pytest runs in a one-time Pod (about 7 minutes)
linux (so the Module 4 seed job can run), and limit resources: under values-lab.yaml of agent: append:
agent:
enabled: true
podRetention: "Never"
customJenkinsLabels: ["linux"]
containerCap: 6
resources:
requests: { cpu: "250m", memory: "256Mi" }
limits: { cpu: "1", memory: "768Mi" }
cd ~/jenkinslab/k8s
helm upgrade --install jenkins jenkins/jenkins -n jenkins --version 5.13.3 -f values-lab.yaml
kubectl -n jenkins get pod jenkins-0 -o jsonpath='{.status.containerStatuses[?(@.name=="jenkins")].restartCount}{"\n"}'
Release "jenkins" has been upgraded. Happy Helming! ... 0
The agent settings are in the default JCasC generated by the chart, so they are hot-reloaded without a restart.
linux -labeled Pod agent):
kubectl -n jenkins get pods -w & # watch curl -sO http://127.0.0.1:8081/jnlpJars/jenkins-cli.jar java -jar jenkins-cli.jar -s http://127.0.0.1:8081/ -auth "admin:$PW" build platform/seed -s | tail -2
default-7m4qf 0/1 Pending 0 0s default-7m4qf 0/1 ContainerCreating 0 1s default-7m4qf 1/1 Running 0 6s default-7m4qf 1/1 Terminating 0 31s Completed platform/seed #1 : SUCCESS
The default template's podName is default, so the Pod name is default-xxxxx. The seed generated myapp/myapp and other jobs (from the Module 2 DSL repo).
lab/jenkins-jobs add jobs/myapp-k8s.groovy and push, then run the seed once more:
pipelineJob('myapp/k8s-pytest') {
description('Run myapp pytest in a Kubernetes Pod agent')
definition {
cpsScm {
scm { git { remote { url('http://gitea:3000/lab/myapp.git'); credentials('gitea-myapp') }; branch('*/main') } }
scriptPath('ci/Jenkinsfile.k8s')
}
}
}ci/Jenkinsfile.k8s (contents in the “Commands” tab) and push, then run:
cd ~/work/myapp && mkdir -p ci # after saving ci/Jenkinsfile.k8s: git add ci/Jenkinsfile.k8s && git commit -m "ci: k8s pod agent pipeline" && git push origin main java -jar ~/jenkinslab/k8s/jenkins-cli.jar -s http://127.0.0.1:8081/ -auth "admin:$PW" build myapp/k8s-pytest -s -v | grep -E 'Created Pod|Running on|passed|Finished'
Created Pod: kubernetes jenkins/myapp-k8s-pytest-1-0kq3d-6t2bz Running on myapp-k8s-pytest-1-0kq3d-6t2bz in /home/jenkins/agent/workspace/myapp/k8s-pytest 4 passed in 0.41s Finished: SUCCESS
kubectl -n jenkins get pods -l app.kubernetes.io/part-of=myapp-ci -o jsonpath='{range .items[*]}{.metadata.name}{" containers="}{.spec.containers[*].name}{" sa="}{.spec.serviceAccountName}{"\n"}{end}'
kubectl auth can-i create pods/exec -n jenkins --as=system:serviceaccount:jenkins:jenkins
myapp-k8s-pytest-2-8kd1x-0zq9w containers=python jnlp sa=default yes
The controller's ServiceAccount jenkins has pods/exec; the inline Pod YAML in this example does not specify serviceAccountName, so the agent Pod uses the namespace's default SA (the chart's default template is determined by agent.useDefaultServiceAccount/serviceAccountAgent , and if no dedicated SA is created it is also default. In production, give agents a separate low-privilege SA and disable unneeded token mounts.
pyhton:3.13-slim push and run; observe the ErrImagePull/ImagePullBackOff message in the console and the kubectl -n jenkins describe pod event, then change it back.kubectl -n jenkins get pods only jenkins-0 remains. Keep the release for later modules.Case 1: isolate agents by team
Problem: Multiple teams share one controller, and team A's build Pods can access team B's database. Approach: Define a Cloud or template for each team, using a separate namespace ci-team-a (the plugin's cloud can create Pods in other namespaces, with the appropriate Role), with NetworkPolicy, ResourceQuota, and a low-privilege ServiceAccount; use folder properties to restrict which jobs can use which Cloud. Limits: The controller is still shared; strong isolation requires multiple controllers (Lesson 6).
Case 2: pip/npm dependency downloads slow every build
Problem: One-time Pods have no cache, so every build spends 2 minutes downloading dependencies. Approach: Deploy an artifact proxy (Nexus/Artifactory/devpi), and set in the Pod environment variables PIP_INDEX_URL; or mount a read-only cache PVC for the template. Limits: A shared writable cache reintroduces cross-build pollution and concurrent write problems.
Case 3: builds queue for 20 minutes at peak
Problem: Commits concentrate at 10 o'clock every day, and builds queue. Approach: Observe default_jenkins_executors_queue_length (Module 7) and the reasons for Pod Pending: containerCap too low → raise it; insufficient nodes → cluster autoscaling (AKS Cluster Autoscaler / Karpenter); slow image pulls → pre-pull images (DaemonSet) or use smaller images. Limits: Node scale-up usually takes minutes; low-priority “placeholder Pods” can reserve capacity.
Common errors and fixes
‘myapp-k8s-pytest-3-qwt6v-x1z2c’ is offline / Still waiting to schedule task
Cause: The Pod is created but the agent has not connected yet: image pulling, Pod Pending (insufficient resources), or the jnlp cannot connect to the controller.
kubectl -n jenkins get pods kubectl -n jenkins describe pod myapp-k8s-pytest-3-qwt6v-x1z2c | tail -20 kubectl -n jenkins logs myapp-k8s-pytest-3-qwt6v-x1z2c -c jnlp | tail
Fix: Handle according to the events: Insufficient cpu/memory → lower requests or scale up; ErrImagePull → fix the image; connection errors in the jnlp log → see the next item.
pods is forbidden: User "system:serviceaccount:jenkins:jenkins" cannot create resource "pods" in API group "" in the namespace "ci-team-a"
Cause: The namespace configured in the Cloud is not the same as the namespace of the Role created by the chart, or rbac.create: false.
kubectl auth can-i create pods -n ci-team-a --as=system:serviceaccount:jenkins:jenkins
Fix: Create a Role (pods, pods/exec, pods/log, events, etc.) in the target namespace and a RoleBinding to jenkins:jenkins.
java.io.IOException: Failed to connect to jenkins-agent.jenkins.svc.cluster.local:50000 / Connection refused
Cause: A NetworkPolicy blocks traffic, the agent listening port is not enabled, or the tunnel address is unreachable across clusters.
kubectl -n jenkins get svc jenkins-agent kubectl -n jenkins get networkpolicy
Fix: Allow agent Pod → controller traffic on 50000/8080; or enable agent.websocket: true so it uses only HTTP(S).
ERROR: Unable to create pod … Timed out waiting for pod (600 s) / Pod has failed: Back-off pulling image
Cause: The image does not exist, or the private registry lacks imagePullSecrets; exceeded waitForPodSec.
Fix: Correct the image name; add to the template imagePullSecrets (matching registry-creds the docker-registry Secret).
process apparently never started in /home/jenkins/agent/workspace/…@tmp/durable-…
Cause: The tool container is missing sh (distroless image), workdir permissions are inconsistent (different containers have different UIDs), or the container has already exited.
Fix: The tool image must include /bin/sh; set a consistent securityContext.runAsUser/fsGroup for the Pod; keep the tool container running using sleep infinity so that it stays alive.
1. If you want to keep the Pod after a build fails for troubleshooting, how should you configure it? How do you clean it up after troubleshooting?
# template or chart: agent.podRetention: "OnFailure" (in JCasC it is podRetention: onFailure) kubectl -n jenkins get pods -l app.kubernetes.io/part-of=myapp-ci kubectl -n jenkins delete pod POD_NAME
Use the casing given in this instance's JCasC Reference for values.
2. With one command, list all Pods in the jenkins namespace that are not the controller, along with their status.
kubectl -n jenkins get pods --field-selector=metadata.name!=jenkins-0 -o wide
A developer added privileged: true and hostPath /var/run/docker.sock to Pod YAML to build images. How would you evaluate and replace this?
Risk: a privileged container or the host Docker socket is equivalent to node root; it can read other Pods' data and credentials on the same node, and even control the node. Alternatives: enable Pod Security Admission on the namespace restricted/baseline to block such Pods; use rootless BuildKit or other privilege-free approaches for image builds, or hand it off to a dedicated build service / separate node pool; combine with NetworkPolicy and least-privilege SAs. Lesson 6 covers how to restrict, on the Jenkins side, who can define Pod templates.
Verified teaching videos
Official docs
- plugins.jenkins.io: Kubernetes (README: Pod template, container step, configuration options)
- Jenkins Handbook: Scaling Jenkins on Kubernetes
- jenkinsci/kubernetes-plugin (examples directory)
Video storyboard (about 100 seconds)
This courseware cannot directly generate video/MP3, but storyboards and narration scripts are provided.
Visual: a gray build block appears in the queue, labeled myapp k8s-pytest.
Narration: the build enters the queue and needs an agent with a specific label, but there is none right now.
Visual: the controller sends a “Pod request form” flying to the apiserver, the scheduler stamps it, and the kubelet pulls two images.
Narration: the Kubernetes plugin calls the API to create the Pod, the scheduler picks a node, and the kubelet starts the jnlp and python containers.
Visual: the jnlp container extends a line back to the controller, and the node icon turns from gray to green.
Narration: the jnlp container connects back to the controller with a one-time secret, and the Pod becomes an online agent.
Visual: the sh command enters the python container via an exec arrow; after the tests pass, the Pod fades out.
Narration: each sh step runs in the tool container through the exec interface. When the build ends, the Pod is deleted, and the next build gets a fresh environment.
Module 6 · Backup, restore, and upgrade strategy
- Describe the role of each type of data in JENKINS_HOME, whether it can be rebuilt from Git, and whether it must be backed up; in particular, understand
secrets/andcredentials.xml's relationship. - Compare PVC snapshots, file-level tar, the thinBackup plugin, Velero, and other methods, define RPO/RTO; complete a “delete release → restore → verify” drill on kind.
- Define an upgrade process on the LTS cadence: read the upgrade guide, validate in staging, the order of plugins and core, the maintenance window, and the rollback plan.
What: what exactly needs protecting
| Contents of JENKINS_HOME | Role | Rebuildable from Git? | Backup recommendation |
|---|---|---|---|
config.xml,*.xml (global plugin configuration),nodes/ | system configuration | ✓ (JCasC) | Still recommended to back up, for faster recovery |
jobs/*/config.xml | Job definitions | ✓ (Job DSL / multibranch scanning) | Back up |
jobs/*/builds/,nextBuildNumber,fingerprints/ | build history, logs, test reports, artifact records | ✗ | Required (often needed for compliance audits) |
secrets/ (such as master.key,hudson.util.Secret) | encryption credentials.xml and the keys for secret fields in each XML | ✗ | Required, and stored encrypted separately from backups |
credentials.xml,users/ | encrypted credentials, user and API tokens | partially (credentials declared in JCasC can be rebuilt) | Required |
plugins/ | Installed plugins (.jpi and extracted directories) | ✓ (plugins.txt / image) | can be excluded; but useful for precise rollback |
workspace/,caches/,war/,casc_configs/ (Helm) | Temporary data / regeneratable | — | Exclude |
Why: why back up “even with JCasC”
JCasC + Job DSL + shared libraries make configuration's recovery point the “last commit”; but build history, credential keys, user tokens, and multibranch scan state exist only in JENKINS_HOME. If you lose secrets/ then even if you restore credentials.xml it cannot be decrypted — all credentials become invalid.
How: backup method comparison
| Method | Consistency | RPO / RTO | Suitable for |
|---|---|---|---|
| CSI VolumeSnapshot (such as AKS Azure Disk snapshots) | crash-consistent (better after quiet-down) | minutes / minutes | production preferred; kind's local-path does not support snapshots |
File-level tar (kubectl exec … tar) | file-level; files of running builds may be inconsistent | depends on the scheduled job | small instances, drills, migration |
| thinBackup plugin (2.1.5) | can wait for idle / force quiet mode | full + incremental by cron | back up to a second volume, then sync externally to object storage |
| Velero | K8s objects + volumes (snapshot or filesystem backup) | On schedule | whole-namespace migration / disaster recovery |
How: upgrade cadence and order
- LTS cadence: roughly every 12 weeks a new LTS baseline is selected (e.g., 2.568 → 2.580), followed by .1/.2/.3 patches about every 4 weeks; weekly releases come out every week. Production should follow LTS.
- Must-read upgrade guide: for example, the 2.580.1 notes — several detached plugins (including SSH server and JavaMail API) are no longer bundled in the WAR; instances that cannot reach the update center must place them manually in the plugins directory in advance; upgrading directly from 1.577 or earlier requires installing 5 plugins first. 2.580.2 has no changes that need special mention.
- Java: since 2.555.1, only Java 21 or Java 25 is supported; before upgrading core, confirm the image JDK (this lesson uses
-jdk21). - Order: first restore a production backup in staging → upgrade core (image) → use the plugin manager to select plugin versions compatible with the new core →
check-configurationvalidate JCasC → smoke test (seed, shared library, Pod agent build) → production: backup/snapshot → quiet-down → upgrade → verify → cancel quiet-down. - Rollback: after an upgrade, Jenkins may migrate XML to a new format, and plugins may also migrate data; “switching back to the old image” is not the same as rollback, and must be combined with volume snapshots or backups taken before the upgrade.
When: how to set RPO/RTO
Typical targets: configuration RPO = 0 (Git), build history RPO ≤ 24 hours (daily snapshot), RTO ≤ 1 hour (restore from snapshot or backup + Helm reinstall). Teams that must retain build logs for audits should store logs and reports separately in object storage (for example via the artifact manager plugin), rather than relying only on JENKINS_HOME.
Architecture diagram: the recovery model of “configuration in Git, state on volumes”
Flowchart: one LTS upgrade (2.568.3 → 2.580.2)
Interactive simulator: backup scope and restore results
Check the JENKINS_HOME contents to back up, then click “Simulate disaster and restore”. The simulator uses Jenkins' real dependencies to determine which features are available after restore, and estimates backup size (sample data: 200 jobs, 30 days of build history).
Core commands
| Command | Purpose | Notes |
|---|---|---|
quiet-down / cancel-quiet-down (CLI) | Stop accepting new builds / resume | waits for running builds to finish; can take -block -timeout |
kubectl exec jenkins-0 -c jenkins -- tar … | gzip | file-level backup streamed to local | Do not add -t (it corrupts the binary stream) |
helm upgrade … --set controller.replicas=0 | Maintenance mode: stop the controller, keep the PVC | the chart supports replicas set to 0 |
kubectl get volumesnapshot | CSI snapshot | requires a CSI driver and VolumeSnapshotClass (supported on AKS; not supported by default on kind) |
curl …/updateCenter/ / security warnings in Manage Jenkins | View plugin security advisories | subscribe to jenkins.io/security/advisories |
# 1) enter quiet-down mode (wait up to 10 minutes for running builds) java -jar jenkins-cli.jar -s http://127.0.0.1:8081/ -auth "admin:$PW" quiet-down -block -timeout 600000 # 2) file-level backup (exclude regenerable directories) kubectl -n jenkins exec jenkins-0 -c jenkins -- tar -C /var/jenkins_home -czf - \ --exclude=./workspace --exclude=./caches --exclude=./war --exclude=./casc_configs . \ > ~/jenkinslab/backup/jenkins-home-$(date +%Y%m%d-%H%M).tgz # 3) resume scheduling java -jar jenkins-cli.jar -s http://127.0.0.1:8081/ -auth "admin:$PW" cancel-quiet-down ls -lh ~/jenkinslab/backup/ && tar -tzf ~/jenkinslab/backup/jenkins-home-*.tgz | grep -E '^\./(secrets|jobs)/' | head -5
-rw-r--r-- 1 lab lab 61M Nov 16 10:42 jenkins-home-20261116-1042.tgz ./secrets/ ./secrets/master.key ./secrets/hudson.util.Secret ./jobs/ ./jobs/myapp/
unclassified:
thinBackup:
backupPath: "/backup/thin"
fullBackupSchedule: "H 2 * * 0"
diffBackupSchedule: "H 2 * * 1-6"
nrMaxStoredFull: 4
waitForIdle: true
forceQuietModeTimeout: 120
backupBuildResults: true
backupBuildArchive: false
backupPluginArchives: false
excludedFilesRegex: "^.*\\.(log)$"
Fields are taken from the official JCasC demos (thin-backup; requires thinBackup ≥ 2.0). How to verify:/backup/thin appears under FULL-…/DIFF-… directory. Common errors: Backing up to the same PVC means both are lost together if the volume is corrupted; excludedFilesRegex excluding build logs log files; remove this exclusion if audits need build logs. Production use: thinBackup writes to a second volume, then a CronJob syncs it to object storage (encrypted).
Lab 6: backup → delete release → restore → verify (about 7 minutes)
secrets/.mkdir -p ~/jenkinslab/backup && cd ~/jenkinslab/k8s curl -s -u "admin:$PW" 'http://127.0.0.1:8081/job/myapp/job/k8s-pytest/api/json?tree=lastBuild[number,result]' # run the three steps from the “Commands” tab: quiet-down → tar → cancel-quiet-down BK=$(ls -t ~/jenkinslab/backup/jenkins-home-*.tgz | head -1); echo $BK
{"_class":"org.jenkinsci.plugins.workflow.job.WorkflowJob","lastBuild":{"_class":"org.jenkinsci.plugins.workflow.job.WorkflowRun","number":2,"result":"SUCCESS"}}
/home/lab/jenkinslab/backup/jenkins-home-20261116-1042.tgzhelm uninstall jenkins -n jenkins kubectl -n jenkins get pvc,pod
release "jenkins" uninstalled No resources found in jenkins namespace.
Secret jenkins-admin and jenkins-casc-secrets were created manually and are not affected by helm uninstall (kubectl get secret -n jenkins confirm).
helm upgrade --install jenkins jenkins/jenkins -n jenkins --version 5.13.3 -f values-lab.yaml --set controller.replicas=0 kubectl -n jenkins get pvc jenkins
NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE jenkins Pending standard 3s
local-path uses WaitForFirstConsumer, so binding happens only after the restore Pod in the next step mounts it.
kubectl -n jenkins run restore --image=busybox:1.37 --restart=Never --overrides='{
"spec":{"containers":[{"name":"restore","image":"busybox:1.37","command":["sleep","3600"],
"volumeMounts":[{"name":"home","mountPath":"/data"}]}],
"volumes":[{"name":"home","persistentVolumeClaim":{"claimName":"jenkins"}}]}}'
kubectl -n jenkins wait --for=condition=Ready pod/restore --timeout=120s
kubectl -n jenkins exec -i restore -- tar -C /data -xzf - < "$BK"
kubectl -n jenkins exec restore -- sh -c 'chown -R 1000:1000 /data && ls /data | head; ls -l /data/secrets/master.key'
kubectl -n jenkins delete pod restore --now
pod/restore created pod/restore condition met config.xml credentials.xml jobs ... -rw-r--r-- 1 1000 1000 256 Nov 16 10:12 /data/secrets/master.key pod "restore" deleted
helm upgrade --install jenkins jenkins/jenkins -n jenkins --version 5.13.3 -f values-lab.yaml kubectl -n jenkins rollout status statefulset/jenkins --timeout=10m pkill -f 'port-forward svc/jenkins' ; kubectl -n jenkins port-forward svc/jenkins 8081:8080 >/dev/null 2>&1 & sleep 3 curl -s -u "admin:$PW" 'http://127.0.0.1:8081/job/myapp/job/k8s-pytest/api/json?tree=lastBuild[number,result]' java -jar jenkins-cli.jar -s http://127.0.0.1:8081/ -auth "admin:$PW" build myapp/k8s-pytest -s | tail -1
statefulset rolling update complete 1 pods at revision jenkins-6c9d…
{"_class":"org.jenkinsci.plugins.workflow.job.WorkflowJob","lastBuild":{"_class":"org.jenkinsci.plugins.workflow.job.WorkflowRun","number":2,"result":"SUCCESS"}}
Completed myapp/k8s-pytest #3 : SUCCESS
The build number continues from 3 (nextBuildNumber is restored); a successful build shows that gitea-myapp credentials can be decrypted —secrets/ and credentials.xml were restored together.
secrets/, the JCasC-declared gitea-myapp will be rewritten at startup and look normal, but all not declared in JCasC — credentials added manually in the UI — will fail to decrypt. This is also why credentials should be handed to an external credential provider or JCasC whenever possible.rm ~/jenkinslab/backup/*.tgz Only do this once you have confirmed it is no longer needed; the backup file contains encryption keys,do not upload it to a public location.Case 1: daily snapshots on AKS
Problem: The production controller runs on AKS and needs RPO 24 hours and RTO 1 hour. Approach: Azure Disk CSI + VolumeSnapshotClass; a CronJob calls the Jenkins CLI at 02:00 every day quiet-down -block, creates a VolumeSnapshot, and after completion cancel-quiet-down; snapshots are kept for 14 days; each quarter, run a restore drill in jenkins-dr namespace from the snapshot. Limits: Snapshots are in the same region as the source disk; region-level disasters also require cross-region replication (Azure Backup for AKS, or Velero to a storage account in another region).
Case 2: plugin incompatibility after upgrade
Problem: On the night of the LTS upgrade, an old plugin caused multibranch scans to error. Approach: The rollback plan was started: restore the pre-upgrade snapshot + old image tag, restoring service within 30 minutes; the plugin was re-tested in staging, where it was found to be marked deprecated (shown in Manage Jenkins), and replaced with a maintained plugin. Limits: Build records created during the rollback window (data after the snapshot) are lost, so teams need to be notified to re-run builds.
Case 3: emergency patch for a security advisory
Problem: A security advisory discloses a high-severity vulnerability in a plugin. Approach: Image pipeline (Renovate automatically updates plugins.txt) → staging smoke test → production completed within 24 hours; if an immediate upgrade is not possible, follow the advisory's mitigations (disable the plugin or feature). Limits: Relying solely on one-click UI updates bypasses review and testing, which carries greater risk over the long term.
Common errors and fixes
Credentials invalid after restore: javax.crypto.BadPaddingException / Failed to decrypt / credentials page shows an empty password
Cause:secrets/ Not backed up, or does not match credentials.xml come from a different instance / point in time.
kubectl -n jenkins exec jenkins-0 -c jenkins -- ls -l /var/jenkins_home/secrets/
Fix: Restore the matching secrets/; if it cannot be restored, all credentials must be re-entered manually (those declared in JCasC are rebuilt automatically).
jenkins-0 log after startup: java.nio.file.AccessDeniedException: /var/jenkins_home/…
Cause: After restore the file owner is root, but Jenkins runs as UID 1000.
Fix: In the restore Pod, chown -R 1000:1000; the chart default fsGroup: 1000 and fsGroupChangePolicy: OnRootMismatch only recursively change ownership when the group of the root directory does not match.
Startup fails after upgrade: UnsupportedClassVersionError … class file version 65.0
Cause: The new Jenkins/plugin versions require Java 21+ (since 2.555.1), but the image still uses an old JDK, or the custom image is based on an old JDK.
Fix: Use -jdk21 or -jdk25 image; for custom images, update the base image as well.
Backup file corrupted: gzip: stdin: not in gzip format
Cause:kubectl exec Added -t (a TTY converts line endings), or stderr mixed into the output.
Fix: Do not use -t; right after backup, tar -tzf verify it and compute the sha256.
1. Without starting the controller and keeping the data, switch release jenkins to maintenance mode; restore it afterwards.
helm upgrade jenkins jenkins/jenkins -n jenkins --version 5.13.3 -f values-lab.yaml --set controller.replicas=0 # ... maintenance ... helm upgrade jenkins jenkins/jenkins -n jenkins --version 5.13.3 -f values-lab.yaml
2. Verify that the backup package contains the encryption key, and output the package's sha256.
tar -tzf "$BK" | grep -E '^\./secrets/(master\.key|hudson\.util\.Secret)$' && sha256sum "$BK"
Management asks: “We have already made all of Jenkins JCasC-based; why do we still need daily snapshots?” Answer in three points.
① Build history, test reports, artifact fingerprints, and multibranch scan state exist only on the volume, which audits and issue tracing require; ② secrets/ and credentials entered in the UI and user API tokens cannot be rebuilt from Git; ③ upgrade rollback must rely on a data snapshot from before the upgrade, because new versions migrate the on-disk data format. Snapshot retention and frequency can be adjusted for cost, but snapshots cannot be dropped.
Teaching videos
No video verified via YouTube oEmbed that specifically covers Jenkins backup/upgrade was found. Refer to the official docs, and use the storyboard below.
Official docs
- Jenkins Handbook: Backing-up/Restoring Jenkins
- LTS Upgrade Guide: 2.580
- LTS Changelog · LTS Release Line
- Security Advisories
- plugins.jenkins.io: ThinBackup
Video storyboard (about 90 seconds)
This courseware cannot directly generate video/MP3, but storyboards and narration scripts are provided.
Visual: JENKINS_HOME expands into a tree; workspace and caches turn gray; secrets and builds glow.
Narration: not everything is worth backing up. Build history and the secrets directory must be backed up; the workspace can be discarded.
Visual: a key icon flies out of secrets, and credentials.xml turns into gibberish.
Narration: lose the secrets, and the credentials file is just a pile of undecryptable ciphertext.
Visual: after helm uninstall the PVC disappears; then it is restored from the backup package, and the build number keeps incrementing.
Narration: only regular restore drills confirm that backups are really usable.
Visual: seven upgrade-flow blocks light up in turn, with a “snapshot” shield before the last one.
Narration: always snapshot before upgrading. Switching back to the old image alone does not turn already-migrated data back.
Module 7 · Monitoring Jenkins: metrics, logs, and alerts
- Enable the Prometheus metrics plugin, and understand the
/prometheus/endpoint,default_jenkins_*naming, collection interval (default 120 seconds), and whether authentication is required. - Use the chart's
controller.prometheus.*to generate a ServiceMonitor and PrometheusRule, and connect them to Prometheus course'skube-prometheus-stack (releasekps, namespacemonitoring). - Write Jenkins' core alerts (unavailability, queue backlog, build failure rate, disk), and understand how the OpenTelemetry plugin turns each build into a trace.
What: what observability data Jenkins can output
| Signal | Source | Typical content |
|---|---|---|
| Metrics (Prometheus format) | Prometheus metrics plugin (depends on the Metrics plugin) | executors, queue, nodes, build counts and durations, disk, JVM metrics; default path /prometheus/ |
| Trace / metrics / logs (OTLP) | OpenTelemetry plugin | one trace per build (stages, steps, and time waiting for an agent as spans),ci.pipeline.run.duration and metrics; optionally send build logs to a backend |
| Kubernetes-layer metrics | kube-state-metrics, kubelet/cAdvisor | controller Pod restarts, memory, PVC free space, number of Pending agent Pods |
| Logs | Container stdout (kubectl logs jenkins-0 -c jenkins) | startup, JCasC, plugin errors; can be collected by Loki/Fluent Bit |
Why: Jenkins' typical “silent failures”
- Queue backlog (agents won't start, containerCap full, insufficient nodes) — everything looks normal in the UI, but builds just never start.
- JENKINS_HOME disk full — builds fail randomly, and the controller may even be unable to save configuration.
- controller memory/GC pressure — the UI lags and all pipelines slow down (Module 3, Case 2).
- A service's builds keep failing and nobody notices.
How: how the Prometheus plugin works
- The plugin computes metrics in the background at
collectingMetricsPeriodInSeconds(default 120 seconds; can be overridden with the environment variableCOLLECTING_METRICS_PERIOD_IN_SECONDS) and caches them;/prometheus/requests return the cached results — so the queue length can lag by up to about 2 minutes. - The metric name prefix is determined by the “default namespace”, whose default value is
default, so the names aredefault_jenkins_executors_queue_length,default_jenkins_builds_duration_milliseconds_summary,default_jenkins_upetc.; the job name is placed in the labeljenkins_job. - Default endpoint requires no authentication (
useAuthenticatedEndpoint=false); once enabled, it requiresMetrics/Viewpermission, and Prometheus must scrape with credentials. Inside the cluster, it is recommended to pair this with a NetworkPolicy that allows only Prometheus access. - Set in the chart
controller.prometheus.enabled: trueto generate a ServiceMonitor (scraping the Servicejenkins'shttpport, path/prometheus, interval default 60s),alertingrulesand generate a PrometheusRule. Note: chart 5.13.3 does not automatically install the prometheus plugin; you must add it to the plugin list yourself.
How: the OpenTelemetry plugin
After configuring an OTLP endpoint (such as the in-cluster OpenTelemetry Collector otel-collector:4317) the plugin generates a trace for each build: the root span is run, child spans are stages and steps, including the wait time for allocating an agent — this answers exactly whether time is spent queuing or testing. It also exports metrics (such as ci.pipeline.run.duration, and to control cardinality it aggregates jobs into by default #other#, refinable with allow/deny lists) and Jenkins health metrics. The backend can be Grafana Tempo/Jaeger/Elastic, etc.; Prometheus can only receive the metrics part.
When: what to do first
- controller availability + disk + memory (needed from day one);
- queue length / wait time (essential in a Pod agent environment);
- build failure rate and duration (dashboards for teams);
- traces (enable when investigating slow builds; watch the data volume).
Comparison with similar approaches
| Prometheus plugin | OpenTelemetry plugin | GitHub Actions / Azure Pipelines | |
|---|---|---|---|
| Mode | Pull (scrape) | Push (OTLP) | Built-in platform statistics + API/Webhook export |
| Strengths | Alerting, capacity trends | Duration breakdown of a single build | No need to self-host |
| Caveats | Enabling “per-build metrics” causes high cardinality | trace volume grows with the number of builds | limited fine-grained metrics |
/prometheus/ is real-time” — it is computed every 120 seconds by default. ② “Putting build parameters in labels is convenient” — the cardinality of parameter values can be huge and overwhelm Jenkins and Prometheus (the plugin docs explicitly warn). ③ “A Running controller Pod means Jenkins is healthy” — you also need to check the queue, disk, GC, and agent provisioning.Architecture diagram: Jenkins connected to kube-prometheus-stack and OTel
Data flow: from queue backlog to alert notification
Interactive simulator: how a queue backlog becomes an alert
Adjust “new builds per minute” and containerCap, then click “Run 20 minutes”. The simulator advances minute by minute: real Jenkins queue length → metric value refreshed by the plugin every 2 minutes → Prometheus scrapes every minute → rule default_jenkins_executors_queue_length > 3,for: 5m states. Each build runs in a Pod for 3 minutes.
Configuration and queries
| Location / command | Purpose | Notes |
|---|---|---|
curl http://127.0.0.1:8081/prometheus/ | View metrics directly | Note the trailing slash; no credentials are needed if authentication is not enabled |
chart: controller.prometheus.enabled / serviceMonitorAdditionalLabels / alertingrules / alertingRulesAdditionalLabels | generates ServiceMonitor / PrometheusRule | kps selects by default by release: kps label selection |
JCasC: unclassified.prometheusConfiguration | plugin settings (path, namespace, interval, authentication…) | use the key names from this instance's JCasC Reference / export |
JCasC: unclassified.openTelemetry | OTLP endpoint, serviceName | fields come from the plugin repository's JCasC test samples |
controller:
additionalPlugins:
# ...keep the Module 4 plugins...
- prometheus:873.v054598e6e84d # the chart does not install it automatically; it must be added explicitly (this triggers a controller restart)
prometheus:
enabled: true
scrapeInterval: 60s
serviceMonitorAdditionalLabels:
release: kps
alertingRulesAdditionalLabels:
release: kps
alertingrules:
- name: jenkins.rules
rules:
- alert: JenkinsDown
expr: up{namespace="jenkins", service="jenkins"} == 0
for: 3m
labels: { severity: critical }
annotations: { summary: "Jenkins controller cannot be scraped" }
- alert: JenkinsQueueBacklog
expr: default_jenkins_executors_queue_length > 3
for: 5m
labels: { severity: warning }
annotations: { summary: "Jenkins queue backlog of {{ $value }} builds for more than 5 minutes" }
- alert: JenkinsHomeDiskLow
expr: default_jenkins_file_store_available_bytes / default_jenkins_file_store_capacity_bytes < 0.15
for: 10m
labels: { severity: warning }
annotations: { summary: "JENKINS_HOME free space below 15%" }
- alert: JenkinsJobFailing
expr: increase(default_jenkins_builds_failed_build_count[1h]) >= 3
labels: { severity: info }
annotations: { summary: "{{ $labels.jenkins_job }} failed 3 or more times within one hour" }
In the alert annotations, the {{ $value }},{{ $labels.jenkins_job }} are Prometheus template syntax. The chart 5.13.3 PrometheusRule template for alertingrules only does toYaml (without going through tpl), and since Helm does not render the values file itself, they are written verbatim into the PrometheusRule — using helm template … | grep -A3 JenkinsQueueBacklog can confirm this.
# queue length
default_jenkins_executors_queue_length
# running builds (busy executors)
default_jenkins_executors_busy
# failure count per job over the past 1 day
sum by (jenkins_job) (increase(default_jenkins_builds_failed_build_count[1d]))
# build duration P90 (use the actual quantile labels from /prometheus/ output for summary)
default_jenkins_builds_duration_milliseconds_summary{quantile="0.9"}
# number of agent Pods in Pending (kube-state-metrics)
sum(kube_pod_status_phase{namespace="jenkins", phase="Pending"})
unclassified:
openTelemetry:
endpoint: "http://otel-collector.monitoring:4317"
serviceName: "jenkins"
serviceNamespace: "lab"
configurationProperties: "otel.exporter.otlp.protocol=grpc"
Lab 7: have kps scrape Jenkins, and create a queue backlog (about 8 minutes)
kps, namespace monitoring):
helm list -n monitoring kubectl get crd servicemonitors.monitoring.coreos.com prometheusrules.monitoring.coreos.com
If it is not installed, follow the Prometheus & Grafana courseto install it helm upgrade --install kps prometheus-community/kube-prometheus-stack -n monitoring --create-namespace (the chart version and resource settings follow that course).
cd ~/jenkinslab/k8s helm upgrade --install jenkins jenkins/jenkins -n jenkins --version 5.13.3 -f values-lab.yaml kubectl -n jenkins rollout status statefulset/jenkins --timeout=10m kubectl -n jenkins get servicemonitor,prometheusrule
statefulset rolling update complete 1 pods at revision jenkins-7f… NAME AGE servicemonitor.monitoring.coreos.com/jenkins 2m NAME AGE prometheusrule.monitoring.coreos.com/jenkins 2m
Use the actual output for resource names. Because the plugin list changed, the controller restarts — this is exactly the kind of change Module 4 describes as needing a maintenance window.
pkill -f 'port-forward svc/jenkins'; kubectl -n jenkins port-forward svc/jenkins 8081:8080 >/dev/null 2>&1 & sleep 3; curl -s http://127.0.0.1:8081/prometheus/ | grep -E '^default_jenkins_(up|executors_queue_length|executors_busy|version)'
default_jenkins_executors_busy 0.0
default_jenkins_executors_queue_length 0.0
default_jenkins_up 1.0
default_jenkins_version{version="2.580.2",} 1.0kubectl -n monitoring port-forward svc/kps-kube-prometheus-stack-prometheus 9090:9090 >/dev/null 2>&1 & sleep 3; curl -s 'http://127.0.0.1:9090/api/v1/query?query=default_jenkins_up' | python3 -m json.tool | grep -E '"service"|"value"' -A1 | head
The Service name depends on kps' release name and fullnameOverride; use kubectl -n monitoring get svc as the reference (the Prometheus course uses kps-kube-prometheus-stack-prometheus).
agent.containerCap to 2 (hot reload), then trigger 8 builds at once:
sed -i 's/containerCap: 6/containerCap: 2/' values-lab.yaml helm upgrade --install jenkins jenkins/jenkins -n jenkins --version 5.13.3 -f values-lab.yaml for i in $(seq 8); do java -jar jenkins-cli.jar -s http://127.0.0.1:8081/ -auth "admin:$PW" build myapp/k8s-pytest; done sleep 150; curl -s http://127.0.0.1:8081/prometheus/ | grep '^default_jenkins_executors_queue_length'
default_jenkins_executors_queue_length 6.0
After about 5 minutes, on the Alerts page in Prometheus (or curl -s 127.0.0.1:9090/api/v1/alerts) you see JenkinsQueueBacklog change from pending to firing.
sed -i 's/containerCap: 2/containerCap: 6/' values-lab.yaml then helm upgrade; after the queue clears, the alert resolves automatically.opentelemetry:3.1605.v37c3e29857e5 plugin and JCasC openTelemetry configuration, trigger a build, then in Grafana Explore search by service.name="jenkins" to find the trace, and observe the duration of the “waiting for agent” span.Case 1: Monday morning queue backlog
Problem: At 9 a.m. on Mondays many merges land, and builds wait 12 minutes on average. Approach: Put on the dashboard default_jenkins_executors_queue_length and kube_pod_status_phase{phase="Pending"} side by side: high queue + many Pending Pods → insufficient cluster capacity (scale the node pool); high queue + few Pending → containerCap or template instanceCap limits (tune the parameters). Limits: Queue metrics are not split by label; complex cases need the wait span in the OTel trace.
Case 2: JENKINS_HOME disk full
Problem: A job had no build retention policy, and logs and artifacts filled the 50Gi PVC within three months. Approach: Alert on JenkinsHomeDiskLow + kubelet volume metrics; standardize in the shared library buildDiscarder; move artifacts to object storage. Limits: The plugin's disk collection can be slow on cloud storage (the docs warn), so you can disable collectDiskUsage, and use kubelet's kubelet_volume_stats_available_bytes.
Case 3: use traces to prove “where the slowness is”
Problem: Developers complain CI is slow; the platform team thinks the tests are slow. Approach: Enable the OTel plugin; Tempo showed 40% of the time spent on “allocating an agent” and image pulls; after switching to smaller images and pre-pulling on nodes, P50 build duration dropped. Limits: Trace data volume is large, so retention should be short (e.g., 7 days).
Common errors and fixes
No jenkins target in Prometheus, though the ServiceMonitor exists
Cause: The ServiceMonitor lacks the label required by kps (release: kps), or kps' serviceMonitorNamespaceSelector does not include jenkins namespace.
kubectl -n jenkins get servicemonitor jenkins -o jsonpath='{.metadata.labels}{"\n"}'
kubectl -n monitoring get prometheus -o jsonpath='{.items[0].spec.serviceMonitorSelector}{"\n"}'
Fix: Set serviceMonitorAdditionalLabels.release: kps; see the troubleshooting for “serviceMonitorSelector mismatch” in the Prometheus course.
target status down: server returned HTTP status 404 Not Found
Cause: The prometheus plugin is not installed (the chart does not install it automatically), or the path was changed.
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8081/prometheus/
Fix: Add in additionalPlugins prometheus; confirm scrapeEndpoint matches the plugin path.
target status down: server returned HTTP status 403 Forbidden
Cause: Authentication was enabled useAuthenticatedEndpoint, and Prometheus did not send credentials.
Fix: Create a service account with only Metrics/View permission and an API token for scraping; configure basicAuth in the ServiceMonitor (referencing a Secret); or disable authentication and restrict sources with a NetworkPolicy.
The queue is backed up, but default_jenkins_executors_queue_length is still 0
Cause: The plugin computes only every 120 seconds; or you are querying an old Prometheus sample.
Fix: Wait one collection cycle; if you need more responsiveness, set the environment variable COLLECTING_METRICS_PERIOD_IN_SECONDS=30 (controller.containerEnv), but mind the controller overhead.
Prometheus memory spikes; the number of default_jenkins_builds_* time series is huge
Cause:“Per-build metrics” was enabled, or build parameters were used as labels, causing a cardinality explosion.
Fix: Disable perBuildMetrics/appendParamLabel, or set perBuildMetricsMaxAgeInHours/perBuildMetricsMaxBuilds; use metricRelabelings to drop unneeded series.
1. List all metric names exposed by the current Jenkins that start with default_jenkins_executors (deduplicated).
curl -s http://127.0.0.1:8081/prometheus/ | grep -o '^default_jenkins_executors_[a-z_]*' | sort -u
2. Write a PromQL query: the 5 jobs with the most failures in the past 24 hours.
topk(5, sum by (jenkins_job) (increase(default_jenkins_builds_failed_build_count[24h])))
The JenkinsQueueBacklog alert fires around 10:00 every day for 10 minutes and then resolves automatically, and the team has started ignoring it. How would you adjust?
First decide whether there is real impact: combine with OTel or build wait times. If a 10-minute wait is acceptable, raise the threshold or lengthen for, or alert on the longest wait time in the queue instead; if it is not acceptable, handle it through capacity planning (scale ahead of time, raise containerCap, pre-pull images). Principle: an alert must be actionable, otherwise downgrade it to a dashboard metric to avoid alert fatigue.
Verified teaching videos
Official docs
- plugins.jenkins.io: Prometheus metrics(docs/metrics, docs/configuration)
- plugins.jenkins.io: OpenTelemetry
- Jenkins Handbook: Monitoring Jenkins
- This repository: Prometheus & Grafana 8 + 1 hour course
Video storyboard (about 80 seconds)
This courseware cannot directly generate video/MP3, but storyboards and narration scripts are provided.
Visual: a developer stares at a build “waiting for executor”, with a clock ticking.
Narration: the most common Jenkins failure is builds that never start while the UI looks completely normal.
Visual: metric lines scroll on the /prometheus page, with queue_length highlighted; refreshed every two minutes.
Narration: the Prometheus plugin computes metrics every two minutes, and queue length is the most important line.
Visual: the rule changes from pending to firing, and a notification pops up in the chat tool.
Narration: the queue exceeds the threshold for five minutes, the alert fires, and the platform team knows before the developers do.
Visual: a waterfall chart of a build trace, with “allocating agent” taking up a large section.
Narration: OpenTelemetry turns each build into a trace, telling you exactly where the time was spent.
Module 8 · Hours 1–5 recap, self-check, and cleanup
- Use one diagram to explain the problem each of the first five lessons solves and where each sits in a build.
- Complete the Jenkins platform “rebuildability” self-check, and use the troubleshooting decision tree to locate common faults on this lesson's topics.
- Clean up resources as needed: keep the kind environment needed for Lessons 6 and 7, and free the rest.
What: what you built in the first five hours
| Lesson | Topic | Assets left behind | Position in a “build” |
|---|---|---|---|
| Lesson 1 | Core foundations: controller, agent, jobs, credentials | ~/jenkinslab Compose: jenkins / agent1 / gitea; credentials gitea-myapp | queue → label matching → executor |
| Lesson 2 | Production readiness: Declarative Pipeline, multibranch, CPS | myapp's Jenkinsfile, multibranch job | the pipeline is interpreted on the controller, and steps are sent to the agent |
| Lesson 3 | Azure: ACR, credentials to the cloud | resource group rg-jenkins-lab (should already be cleaned up) | build artifacts are pushed to a cloud registry and deployed |
| Lesson 4 | AWS: ECR, credentials to the cloud | ECR repository myapp (should already be cleaned up) | Same as above (AWS) |
| Lesson 5 (this lesson) | Automated operations: JCasC, Job DSL, shared libraries, Helm, Pod agents, backup, monitoring | kind lab release in jenkins; Gitea repositories lab/jenkins-jobs,lab/jenkins-shared-lib; values-lab.yaml; backup package | the platform itself is rebuildable, scalable, and observable |
Why: four questions of platform maturity
- Rebuildable: if you delete the controller, can you recover within 1 hour using only Git + backups? (JCasC, Job DSL, shared libraries, Helm, backups)
- Scalable: at peak, do builds automatically get resources? (Kubernetes plugin, containerCap, cluster scaling)
- Observable: are problems detected before users notice? (metrics, alerts, traces)
- Secure: who can change configuration, and who can execute arbitrary code? (trusted libraries, Job DSL script security, RBAC — covered in depth in Lesson 6)
How: comparison from Compose to Kubernetes
| Concern | Lessons 1–2 (Compose) | Lesson 5 (kind + Helm) |
|---|---|---|
| Configuration | Install wizard + UI | values + JCasC (ConfigMap hot reload) |
| Jobs | Multibranch jobs created in the UI | JCasC bootstraps the seed job → Job DSL |
| Pipeline | full Jenkinsfile in every repo | shared library + two-line Jenkinsfile |
| agent | persistent agent1 (Docker access) | one Pod per build |
| Data | Docker volume jenkins_home | PVC jenkins + backups/snapshots |
| Monitoring | None | ServiceMonitor + PrometheusRule + OTel |
When: what's next
Lesson 6Do security and architecture on this kind environment (authentication, authorization matrix, folder inheritance, Script Security); Lesson 7 does deep troubleshooting and optimization (causes of builds stuck in the queue, performance). So this module's cleanup keeps the kind cluster and release.
Overview diagram: layers of the Jenkins platform
Timeline: capabilities accumulated over five hours
Animation: the end-to-end journey of one commit (linking the five lessons)
Each step is labeled with its lesson, the component that performs it, and where you can see the evidence.
Self-check and cleanup commands
#!/usr/bin/env bash
set -u
J=http://127.0.0.1:8081
PW=$(kubectl -n jenkins get secret jenkins-admin -o jsonpath='{.data.jenkins-admin-password}' | base64 -d)
ok(){ printf ' [OK] %s\n' "$1"; } ; bad(){ printf ' [FAIL] %s\n' "$1"; }
echo "== Lesson 5 self-check =="
helm status jenkins -n jenkins >/dev/null 2>&1 && ok "release jenkins exists" || bad "release jenkins"
[ "$(kubectl -n jenkins get pod jenkins-0 -o jsonpath='{.status.containerStatuses[?(@.name=="jenkins")].ready}')" = "true" ] && ok "controller Ready" || bad "controller"
curl -sf -u "admin:$PW" "$J/api/json?tree=description" | grep -q 'Helm release jenkins' && ok "JCasC systemMessage in effect" || bad "JCasC"
curl -sf -u "admin:$PW" "$J/job/platform/job/seed/api/json" >/dev/null && ok "seed job exists" || bad "seed"
curl -sf -u "admin:$PW" "$J/job/myapp/job/k8s-pytest/lastSuccessfulBuild/api/json" >/dev/null && ok "Pod agent build has succeeded before" || bad "k8s-pytest"
curl -sf "$J/prometheus/" | grep -q '^default_jenkins_up' && ok "Prometheus metrics available" || bad "prometheus"
ls ~/jenkinslab/backup/jenkins-home-*.tgz >/dev/null 2>&1 && ok "backup package exists" || bad "backup"
== Lesson 5 self-check == [OK] release jenkins exists [OK] controller Ready [OK] JCasC systemMessage in effect [OK] seed job exists [OK] Pod agent build succeeded [OK] Prometheus metrics available [OK] backup package exists
Cleanup levels
| Level | Command | Impact |
|---|---|---|
| A. Recommended (keep for Lessons 6 and 7) | docker rm -f jenkins-casc agent-casc; docker volume rm jenkins_casc_home; stop port-forward: pkill -f 'kubectl.*port-forward' | only deletes the temporary instances from Modules 1–2 |
| B. Pause (save resources) | helm upgrade jenkins jenkins/jenkins -n jenkins --version 5.13.3 -f values-lab.yaml --set controller.replicas=0 | controller stopped, PVC kept |
| C. Delete Jenkins | helm uninstall jenkins -n jenkins; kubectl delete ns jenkins | PVC and data are deleted (back up first) |
| D. Clean up everything | kind delete cluster --name lab; docker network disconnect kind "$GITEA_CID" | resources from the Kubernetes, Helm, and Prometheus courses in this cluster will also be deleted |
If Lesson 3/4 cloud resources were not cleaned up: az group delete -n rg-jenkins-lab --yes --no-wait; the AWS ECR repository myapp (ca-central-1) — delete it following the Lesson 4 cleanup steps.
Lab 8: self-check + “rebuild from scratch” drill + cleanup (about 10 minutes)
- Your
values-lab.yamlhas been committed to Gitea (for examplelab/jenkins-config)?git -C ~/jenkinslab/k8s status - Secret
jenkins-admin,jenkins-casc-secretsvalues are also stored safely elsewhere (not only in the cluster)? - Has the most recent backup been
tar -tzfverified and includessecrets/?
jenkins-dr install the release using the same values jenkins-dr (port-forwarded to 8083), restore the latest backup, and confirm myapp/k8s-pytest build history exists. When done, helm uninstall jenkins-dr -n jenkins-dr && kubectl delete ns jenkins-dr. Note: two controllers will scan Gitea at the same time and may build duplicates, so during the drill you may first disable jenkins-dr jobs in it.docker ps --format '{{.Names}}' | grep -E 'jenkins-casc|agent-casc' || echo "temporary instances cleaned up"
kubectl -n jenkins get pods
kind get clusters
temporary instances cleaned up NAME READY STATUS RESTARTS AGE jenkins-0 2/2 Running 0 35m lab
secrets/GITEA_TOKEN and other files have permissions 600 and are not in any Git repository.Case 1: a real controller loss
Problem: During a node pool upgrade, the disk holding the PVC was accidentally corrupted. Approach: The team followed the runbook: new disk ← latest snapshot; helm upgrade --install (values are in Git); JCasC rebuilt the configuration; the seed job regenerated the jobs; Pod agents are stateless and need no recovery. Total time 40 minutes; 6 hours of build history lost (the RPO met the 24-hour target). Lessons learned: Quarterly drills make this kind of recovery “run by the playbook”.
Case 2: the platform team's “paved road”
Problem: Onboarding a new service to CI takes 2 days. Approach: A new service only needs: ① add one line to the services list in jenkins-jobs; ② place a two-line Jenkinsfile at the repo root. The library provides test, build, scan, and release; the Pod template comes from the library's resources. Onboarding time drops to 15 minutes. Limits: Special requirements are met through library parameters or an “escape hatch” (allowing a full Jenkinsfile), but they require review.
Case 3: migrating part of the workload from Jenkins to GitHub Actions
Problem: An open-source component team wants to use GitHub Actions. Approach: Refer to the GitHub course, map each stage in the shared library to a reusable workflow one by one; GitHub Actions Importer can help convert Jenkins pipelines (for its Jenkins support scope, refer to GitHub's documentation). Limits: Groovy logic in the shared library cannot be converted automatically and must be rewritten as scripts or Actions.
Interactive troubleshooting decision tree: JCasC / Helm / Pod agent / monitoring
Start from the symptom, choose step by step, and get diagnostic commands and fixes.
Supplement: the three most commonly used diagnostic commands
kubectl -n jenkins get events --sort-by=.lastTimestamp | tail -20 kubectl -n jenkins logs jenkins-0 -c jenkins --since=15m | grep -E 'SEVERE|WARNING|casc' | tail -20 kubectl -n jenkins logs jenkins-0 -c config-reload --since=15m | tail -10
1. Without opening the UI, list the nodes currently online on the controller (including Pod agents).
curl -s -u "admin:$PW" 'http://127.0.0.1:8081/computer/api/json?tree=computer[displayName,offline]' | python3 -m json.tool
2. Pause Jenkins to save resources while keeping all data.
helm upgrade jenkins jenkins/jenkins -n jenkins --version 5.13.3 -f values-lab.yaml --set controller.replicas=0 kubectl -n jenkins get pvc jenkins # still Bound
A new colleague asks: “Why not just click around in the UI? It's faster.” Use this lesson's content to persuade them (at least four points).
① Rebuildable: after the controller is lost, configuration and jobs can be restored from Git; ② reviewable: configuration changes go through PRs and are audited; ③ consistency: dozens of services share libraries and DSL, avoiding drift; ④ testable: JCasC check-configuration, library unit tests, staging validation of upgrades; ⑤ secure: fewer people hold administrator rights, and UI changes are overwritten by reloads. The cost is learning effort up front, but the benefit grows with scale.
Verified review videos
Video storyboard (about 60 seconds)
This courseware cannot directly generate video/MP3, but storyboards and narration scripts are provided.
Visual: five steps light up in turn, labeled with the five lesson topics.
Narration: five hours, from “it can build” to platform as code.
Visual: one commit lights up its path through Git, the seed job, the shared library, the Pod agent, and metrics.
Narration: one commit passes through every layer of the platform, and every layer is written in Git.
Visual: after the controller icon disappears, it is reassembled from Git and backups.
Narration: the real test is how quickly you can get it back after deleting it.
Command cheat sheet
JCasC
# Environment CASC_JENKINS_CONFIG=/var/jenkins_home/casc_configs JAVA_OPTS=-Djenkins.install.runSetupWizard=false # CLI jenkins-cli check-configuration < jenkins.yaml jenkins-cli apply-configuration < jenkins.yaml jenkins-cli export-configuration > exported.yaml jenkins-cli reload-jcasc-configuration # Token reload (set CASC_RELOAD_TOKEN) curl -X POST "$J/reload-configuration-as-code/?casc-reload-token=$T" # Schema / Reference $J/configuration-as-code/schema $J/manage/configuration-as-code/
Secret interpolation
password: "${GITEA_TOKEN}" # environment variable or /run/secrets/GITEA_TOKEN
value: "${VAR:-default}" # default value (non-secret)
key: "${readFile:/run/secrets/key}" # read file
p12: "${readFileBase64:/secret/c.p12}"
user: "${json:username:${AWS_SECRET}}"
cmd: "echo ^${WORKSPACE}" # literal ${…}
# Helm chart: additionalExistingSecrets
# name: jenkins-casc-secrets, keyName: gitea-token
# → ${jenkins-casc-secrets-gitea-token}Job DSL
jobDsl targets: 'jobs/**/*.groovy',
removedJobAction: 'DISABLE', // IGNORE | DISABLE | DELETE
removedViewAction: 'DELETE',
lookupStrategy: 'JENKINS_ROOT', // or SEED_JOB
failOnMissingPlugin: true
folder('myapp')
pipelineJob('myapp/x') { definition { cpsScm { … } } }
multibranchPipelineJob('myapp/myapp') {
branchSources { git { id('stable-id'); remote(url); credentialsId('gitea-myapp') } }
}
// API Viewer: $J/plugin/job-dsl/api-viewer/index.htmlShared Library
@Library('lab-shared@v1.0') _ // compile time
library "lab-shared@${env.BRANCH_NAME}" // runtime (variables allowed)
def y = libraryResource 'org/lab/pod-python.yaml'
// vars/xxx.groovy: def call(Map cfg = [:]) { … }
// src/org/lab/X.groovy: class X implements Serializable
// JCasC: unclassified.globalLibraries.libraries[]
// name, defaultVersion, allowVersionOverride, implicit,
// retriever.modernSCM.scm.git.remote / credentialsIdHelm (release jenkins)
helm repo add jenkins https://charts.jenkins.io
helm upgrade --install jenkins jenkins/jenkins -n jenkins \
--version 5.13.3 -f values-lab.yaml
helm get values jenkins -n jenkins
helm template jenkins jenkins/jenkins --version 5.13.3 -f values-lab.yaml
kubectl -n jenkins port-forward svc/jenkins 8081:8080
kubectl -n jenkins logs jenkins-0 -c init # plugin installation
kubectl -n jenkins logs jenkins-0 -c config-reload # hot reload
kubectl -n jenkins get secret jenkins-admin \
-o jsonpath='{.data.jenkins-admin-password}' | base64 -dPod agent
agent {
kubernetes {
yaml '''…Pod YAML…''' // or yamlFile 'ci/pod.yaml'
defaultContainer 'python'
}
}
container('jnlp') { sh 'hostname' }
podTemplate(yaml: y) { node(POD_LABEL) { container('python') { … } } }
// chart: agent.containerCap / customJenkinsLabels / podRetention
// agent.websocket / resourcesBackup and upgrade
jenkins-cli quiet-down -block -timeout 600000 kubectl -n jenkins exec jenkins-0 -c jenkins -- tar -C /var/jenkins_home -czf - \ --exclude=./workspace --exclude=./caches --exclude=./war --exclude=./casc_configs . > home.tgz jenkins-cli cancel-quiet-down helm upgrade … --set controller.replicas=0 # maintenance mode tar -tzf home.tgz | grep secrets/master.key # verify # LTS-compatible plugin versions: curl -sL "https://updates.jenkins.io/update-center.actual.json?version=2.580.2"
Monitoring
default_jenkins_up
default_jenkins_executors_queue_length # refreshed every 120s
default_jenkins_executors_busy
increase(default_jenkins_builds_failed_build_count[1h])
default_jenkins_file_store_available_bytes / default_jenkins_file_store_capacity_bytes
sum(kube_pod_status_phase{namespace="jenkins",phase="Pending"})
# chart: controller.prometheus.enabled + serviceMonitorAdditionalLabels {release: kps}
# the plugin must be added explicitly: prometheus:873.v054598e6e84dQuick troubleshooting table
| Symptom | Check first | Common causes |
|---|---|---|
| controller exits right after startup | logs -c jenkins | grep -i casc | invalid JCasC field, the plugin for the root element is not installed, configuration conflict |
| jenkins-0 stuck in Init | logs -c init | plugin download failure, plugin requires a higher core |
| JCasC change has no effect | logs -c config-reload, casc_configs content | ConfigMap propagation delay, YAML error causing reload rejection, concurrent reload 409 |
| builds stay queued | get pods -n jenkins, build console | label mismatch, containerCap full, Pod Pending, agent connect-back failure |
| No such DSL method | build log starts with Loading library | library not loaded, file name casing |
| script not yet approved | In-process Script Approval | Job DSL script security |
| credentials invalid after restore | ls secrets/ | secrets/ not backed up or does not match |
| Prometheus has no target | ServiceMonitor labels | missing release: kps, plugin not installed |
Recommended configuration snippet (production starting point)
controller:
image: { repository: "registry.example.com/platform/jenkins", tag: "2.580.2-jdk21-p20261116" }
installPlugins: false # plugins are pre-installed in the image
numExecutors: 0
resources: { requests: { cpu: "2", memory: "4Gi" }, limits: { memory: "4Gi" } }
javaOpts: "-XX:MaxRAMPercentage=70"
admin: { existingSecret: jenkins-admin }
prometheus: { enabled: true, serviceMonitorAdditionalLabels: { release: kps } }
persistence:
size: 50Gi
annotations: { "helm.sh/resource-policy": keep }
agent:
containerCap: 30
podRetention: "Never"
networkPolicy:
enabled: true
Capstone lab + final quiz
Scenario
The platform team must prove that Jenkins is “rebuildable”. Requirements: all configuration comes from Git (values + JCasC, jenkins-jobs, jenkins-shared-lib), and build history comes from backups; after the rebuild, a myapp Pod agent build succeeds and metrics and alerts work. Throughout, make no configuration changes in the UI.
lab/jenkins-config, commit values-lab.yaml (containing no secrets) and a README.md runbook (recovery steps, where secrets are stored).
cd ~/jenkinslab/k8s && git init -b main && git add values-lab.yaml && git commit -m "jenkins platform config" git push "http://lab:$(cat ~/jenkinslab/casc-lab/secrets/GITEA_TOKEN)@127.0.0.1:3000/lab/jenkins-config.git" main # create this repo in Gitea first
tar -tzf confirm it includes secrets/master.key, and record the sha256.myapp/k8s-pytest 's lastBuild number,platform/seed the list of generated jobs (list-jobs myapp).helm uninstall jenkins -n jenkins, and confirm the PVC is deleted.git clone jenkins-config; helm upgrade --install … --set controller.replicas=0 restore the backup with a temporary Pod and chown 1000:1000; then upgrade with the normal values.myapp/k8s-pytest, the build number should continue after the baseline; observe Pod creation and deletion.default_jenkins_up == 1; trigger again with containerCap=2 + 8 builds JenkinsQueueBacklog, then restore.Acceptance checklist
Open-ended self-check (6 questions)
1. What does each of JCasC, Job DSL, and Shared Library manage? Why can't they replace each other?
JCasC manages the controller's system configuration (security, credentials, cloud, global plugin settings); Job DSL manages which jobs exist and their configuration; shared libraries manage pipeline runtime logic. The three act on different objects and run at different times (startup/reload, seed run, build run), and JCasC can only jobs: invoke Job DSL to bootstrap a few jobs.
2. Explain the components of the queue time for a Pod agent build, and how each can be optimized.
Provisioning decision (the no-delay strategy has already minimized it), Pod scheduling (node capacity, size of requests), image pull (image size, pre-pulling, image cache), container start, remoting connect-back (network, WebSocket/TCP). Optimizations: small images, reasonable requests, cluster autoscaling, pre-pulling with a DaemonSet, appropriate containerCap, monitoring Pending causes.
3. Why is it said that “write access to the global trusted library's repo = Jenkins administrator rights”?
A trusted library does not go through the Groovy sandbox and can call Jenkins.get() any API, such as reading credentials and changing security settings. Anyone who can push code to its default version can execute arbitrary code on the controller as SYSTEM.
4. In Helm, how do changing only JCasC and changing plugins take effect differently? What does this mean for the release process?
A JCasC change → ConfigMap → config-reload sidecar → reload API, no restart; a plugin/image/JVM change → Pod template checksum changes → StatefulSet recreates the Pod, which interrupts running builds. The former can be released at any time; the latter needs a maintenance window and quiet-down.
5. Design Jenkins' RPO/RTO and backup plan (production AKS).
Configuration RPO 0 (Git); state RPO 24h: daily VolumeSnapshot + pre-upgrade snapshot, retained 14 days, cross-region replication; secrets/ also store in Key Vault; RTO 1h: runbook + quarterly drills; build logs/artifacts moved to object storage to satisfy audits.
6. List 4 alerts you would configure for Jenkins, and explain the action plan for each.
JenkinsDown (check Pod/events/logs; restore from snapshot if needed); QueueBacklog (check Pending Pods and containerCap; scale out or tune); HomeDiskLow (clean up build retention, expand the PVC, move artifacts); JobFailing (notify the owning team; if several jobs fail at once, check the shared library, credentials, and external dependencies).
Sources and version notes
| Topic | Verification result | Source (accessed 2026-11-16) |
|---|---|---|
| Jenkins LTS / weekly | LTS 2.580.2 (2026-10-28), 2.580.1 (2026-09-30), 2.568.3 (2026-09-02); weekly 2.590 (2026-11-10) | jenkins.io/changelog-stable; update-center.actual.json |
| Java requirement | Since 2.555.1, only Java 21 or Java 25 is supported | LTS changelog |
| 2.580 upgrade guide | 2.580.1: some detached plugins are no longer bundled with the WAR; upgrading directly from 1.577 or earlier requires installing 5 plugins first. 2.580.2 has no special notes | upgrade-guide/2.580 |
| Helm chart | jenkins 5.13.3 (2026-11-15, appVersion 2.580.2, default image 2.580.2-jdk25, k8s-sidecar 2.14.3, inbound-agent 3395.v6e5377b_0fb_3c-5-jdk25); repository https://charts.jenkins.io, OCI ghcr.io/jenkinsci/helm-charts/jenkins | helm-charts releases, Chart.yaml, values.yaml, templates/* |
| Chart behavior | init containers config-reload-init, init; sidecar config-reload calls /reload-configuration-as-code/?casc-reload-token=$(POD_NAME); PVC is a regular template resource; PrometheusRule applies only toYaml to alertingrules; the chart does not auto-install the prometheus plugin; Role name <release>-schedule-agents | charts/jenkins/templates (_helpers.tpl, jenkins-controller-statefulset.yaml, home-pvc.yaml, rbac.yaml, config.yaml, jenkins-controller-alerting-rules.yaml) |
| Plugin versions (LTS-compatible) | configuration-as-code 2147.v8a_8d38668c72 (core ≥ 2.541.1); job-dsl 3732.v9a_c49a_61a_313; kubernetes 4560.vc25b_83890c34 (≥ 2.516.3); pipeline-groovy-lib 822.vc95f70dea_db_7; prometheus 873.v054598e6e84d (≥ 2.555.3); opentelemetry 3.1605.v37c3e29857e5; matrix-auth 3.3; gitea 286.v0740a_413c1eb_; git 5.11.0; workflow-aggregator 608.v67378e9d3db_1; credentials 1514.vb_01eb_014e7d4; thinBackup 2.1.5; junit 1458.1460.vd53b_087eeb_2c (LTS-compatible; latest 1463.v7508416a_349c requires 2.589) | update center (version=2.580.2),plugins.jenkins.io |
| JCasC mechanism | initialized after SYSTEM_CONFIG_LOADED and before SYSTEM_CONFIG_ADAPTED; default errorOnConflict merge; original error messages; SecretSource (environment variables, /run/secrets, Vault, Key Vault, AWS); reload method and 409; CLI command name | configuration-as-code-plugin(ConfigurationAsCode.java, yaml/*MergeStrategy.java, SecretSourceResolver.java, docs/features/secrets.adoc, configurationReload.md, demos/*) |
| Job DSL | Steps jobDsl parameters; useScriptSecurity default true; the error message for sandbox needing a specified user | job-dsl-plugin(ExecuteDslScripts.java, GlobalJobDslSecurityConfiguration.groovy, Messages.properties); JCasC demos/jobs |
| Shared Library | “Global Trusted Pipeline Libraries” and untrusted libraries; original error messages | pipeline-groovy-lib-plugin(LibraryAdder, LibraryConfiguration, Messages.properties);Handbook |
| Prometheus plugin | default path prometheus, namespace default, job label jenkins_job, collection interval 120s, no authentication by default; metric name list | prometheus-plugin(PrometheusConfiguration.java, docs/metrics/index.md, docs/configuration/configuration.md) |
| OpenTelemetry plugin | JCasC keys unclassified.openTelemetry (endpoint, serviceName, serviceNamespace…); ci.pipeline.run.duration default aggregation into #other# | opentelemetry-plugin(docs/monitoring-metrics.md, jcasc test resources) |
| kind / Kubernetes / Helm | kind v0.33.0, kindest/node v1.37.0, Helm 4.3.x — reuses the facts already verified in this repository's Kubernetes and Helm courses | K8s course · Helm course |
| kube-prometheus-stack | release kps, namespace monitoring, selector labels release: kps, Service kps-kube-prometheus-stack-prometheus — follows the Prometheus course conventions | Prometheus & Grafana course |
Video verification notes
All videos were verified via YouTube oEmbed (https://www.youtube.com/oembed?url=…&format=json) on 2026-11-16 for title and channel:
| Video ID | Title | Channel | Where used |
|---|---|---|---|
| ZXaorni-icg | How to Use Kubernetes Pods As Jenkins Agents | CloudBeesTV | Modules 4, 5 |
| 3H9eNIf9KZs | How to Monitor Jenkins With Grafana and Prometheus | CloudBeesTV | Module 7 |
| AHSHksfg1BE | Monitoring Production grade Jenkins using Prometheus, Grafana & InfluxDB | Monitoring With Grafana | Deekshith SN | Module 7 |
| 7KCS70sCoK0 | Complete Jenkins Pipeline Tutorial | Jenkinsfile explained | TechWorld with Nana | Module 3 |
| ORNDwYXa4nQ | Continuous Delivery: Pipeline As Code With Jenkins | Eclipse Foundation | Module 2 |
| 6YZvp2GwT0A | Learn Jenkins! Complete Jenkins Course - Zero to Hero | DevOps Journey | Modules 1, 8 |
| f4idgaq2VqA | Jenkins Tutorial – How to Deploy a Test Server with Docker + Linux (Full Course) | freeCodeCamp.org | Module 8 |
| pMO26j2OUME | Run Jenkins in Docker Container - Jenkins Pipeline Tutorial for Beginners 1/4 | TechWorld with Nana | Module 8 |
No verified dedicated videos were found for: JCasC, Job DSL seed jobs, the Shared Library topic, the jenkinsci Helm chart, or Jenkins backup/upgrade. These modules provide storyboard scripts instead. Videos were generally recorded before the versions used in this lesson, so for interface and version details, this lesson takes precedence.
Audio notes
The "Audio" tab uses the browser's built-in Web Speech API to read the Chinese narration scripts (zh-CN) and English terms (en-US) aloud. This courseware is offline HTML and cannot embed MP3 audio; the narration scripts can be handed directly to another TTS tool or used as a recording script.
Known limitations
- All commands in this lesson have not been run in the authoring environment; all expected outputs are examples, and timestamps, random Pod name suffixes, build numbers, file sizes, revision numbers, and similar values are illustrative.
- Plugin versions change very frequently; when you work through this, use
update-center.actual.json?version=<your LTS>to look up compatible versions. The chart's default plugin versions also change with the chart version. - Some plugin key names in JCasC (such as
prometheusConfiguration,globalJobDslSecurityConfiguration,podRetentionand the casing of their values) are derived from plugin class names and symbols; use your instance's Configuration as Code Reference or an export as the authority. - Job DSL dynamic DSL methods (such as the Gitea branch source
gitea { … }) depend on the plugin version, so the instance's API Viewer is authoritative; the main course path uses the stablegitbranch source. - The approach of making Gitea reachable from Pods after joining the kind network, using the name
gitea, relies on the Docker DNS behavior of kind nodes; it is a lab technique. If resolution fails, use an IP address or hostAliases instead. busybox:1.37,jenkins/inbound-agent:latest-jdk21and similar image tags have not each been checked for release dates; use Docker Hub as the reference. In production, pin to a specific version or digest.- Options for building container images inside a Pod (rootless BuildKit and similar) are only mentioned in this lesson, without a full configuration. For cloud push and deployment, see Lessons 3 and 4.
- GitHub Actions Importer's Jenkins support scope and Jenkins' native OIDC token capabilities are not covered in this lesson; refer to the GitHub documentation and Lessons 3, 4, and 6.