Jenkins Hour 5: Automated Operations — Configuration as Code and Jenkins on Kubernetes

Turn the Jenkins you built in Lesson 1 by clicking through the wizard into code that is reviewable, rebuildable, upgradable, and observable; then move it to a kind cluster lab, so that every build runs in a disposable Pod
Jenkins LTS 2.580.2Helm chart jenkins 5.13.3configuration-as-code 2147.v8a_8d38668c72kubernetes 4560.vc25b_83890c34Verified against official sources · 2026-11-16
Overall Learning Goals
  • 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 lab namespace jenkins to deploy the release jenkins, 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

#TimeModuleCore contentAnimation / interactionLab
0Before classSetup: kind cluster and HelmCheck ~/jenkinslab (Lessons 1–2), create or reuse a kind cluster lab, install Helm 4, add the jenkins chart repositoryEnvironment self-check checklistkind get clusters,helm search repo jenkins
100–06Configuration as Code (JCasC)Root element, loading order (after SYSTEM_CONFIG_LOADED), multi-file merging, secret interpolation ${…}, export, hot reloadCore animation: JCasC reads YAML → validates → configurator writes into the Jenkins object modelRewrite the wizard configuration as jenkins.yaml, and start a fresh container on port 8082 without the wizard
206–13Job DSL and Seed JobsDSL syntax, seed job, JCasC jobs:, script security, removedJobAction, generating multibranch jobsSeed job generate/delete job simulatorUse DSL to generate a folder + pipeline + myapp multibranch job
313–21Shared Libraries: Reusable PipelinesDirectory structure,@Library, implicit loading, version pinning, trusted vs. sandbox, unit testsLibrary resolution and loading animationPublish to Gitea lab/jenkins-shared-lib and call it from myapp
421–28Run Jenkins on Kubernetes with Helmchart structure, values, plugin-install init container, JCasC ConfigMap + config-reload sidecar, persistence, RBACresources become ready in order after helm installin the namespace jenkins install the release jenkins
528–35Kubernetes plugin: dynamic Pod agentscloud / podTemplate,agent { kubernetes { yaml … } },container(), jnlp container, connection method, quotas and cleanupCore animation: queued build → Pod creation → agent connects back → execution → deletionmyapp's pytest runs in a python:3.13-slim Pod
635–42Backup, restore, and upgrade strategyJENKINS_HOME structure, secrets, PVC snapshot / tar / thinBackup, RPO/RTO, LTS upgrade process, plugin pinningBackup scope selector + restore drilltar backup → delete release → restore → verify
742–50Monitoring Jenkins: metrics, logs, and alertsPrometheus plugin /prometheus/, ServiceMonitor, key metrics and alerts, OpenTelemetry tracingqueue backlog → alert-firing simulatorkube-prometheus-stack (release kps) scrapes Jenkins
850–60Hours 1–5 recap, self-check, and cleanupEnd-to-end chain: commit → scan → shared library → Pod agent → build → metrics; cleanup and costEnd-to-end journey of one commit + troubleshooting treeSelf-check + cleanup (keep the kind cluster for Lessons 6 and 7)
—After classCheat sheet · Capstone lab“Delete Jenkins, rebuild from Git within 30 minutes”Final quiz (12 questions)Capstone lab

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key commands / configLab
Describe the entire controller configuration in YAML✓··✓✓✓✓✓CASC_JENKINS_CONFIG,controller.JCasC.configScriptsM1, M4
Inject secrets safely (not in Git)✓··✓·✓··${VAR},/run/secrets,existingSecretM1, M4
Jobs as code·✓·✓···✓jobs:,pipelineJob,multibranchPipelineJobM2
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 jenkinsM4
Elastic build resources (Pod agents)···✓✓·✓✓agent { kubernetes { … } },container('python')M5
Backup, restore, upgrade✓··✓·✓·✓tar --exclude=workspace,controller.replicas: 0M6
Metrics, tracing, and alerts····✓·✓✓/prometheus/,default_jenkins_executors_queue_lengthM7

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

TopicWhy not in this lessonWhere 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-stackThis lesson only covers “what Jenkins exposes and what to alert on”Prometheus & Grafana 8 + 1 hour course
kind, Pod, Service, PVC, RBAC basicsCovered in the Kubernetes basics courseKubernetes 8 + 1 hour course
Jenkins authentication (OIDC / SAML / Entra), permission matrix, Script Security approvalBelongs to the security topicLesson 6(will reuse this lesson's kind environment)
stuck queues, performance tuning, splitting large controllersBelongs to advanced troubleshootingLesson 7 (also reuses this lesson's kind environment)
Similar practices in GitHub Actions / Azure Pipelines (reusable workflows, templates)Different productsGitHub course · Azure DevOps course

How to use this courseware

10 pages per module
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.
Learning progress
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).
Chinese audio
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.
Version notes (verified 2026-11-16) Current Jenkins LTS is 2.580.2 (2026-10-28), and the weekly is 2.590 (2026-11-10); since 2.555.1 it only supports Java 21 or Java 25. The official Helm chart 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.
Relationship to earlier lessons Lessons 1–2 ran in ~/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)

Confirm the Lesson 1–2 Compose lab environment still works, then prepare the kind cluster lab, namespace jenkins and Helm 4
Before class ≈ 10 minkind v0.33.0 · Kubernetes v1.37Helm 4.3.x
Prerequisites
  • CompletedLesson 1andLesson 2: ~/jenkinslab/compose.yaml contains jenkins,agent1,gitea three services; Gitea has users/organizations lab and a repository lab/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
Why pin the digest? The kind release notes recommend using the node image @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
Notes and risks kind nodes are containers connected to the Docker network 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 lab and namespace jenkins; Lessons 6 and 7 continue to use them. For full cleanup, see Module 8.

Self-check checklist

Module 1 · Configuration as Code (JCasC)

00:00 – 06:00 · Turn every button clicked in the install wizard into a reviewable jenkins.yaml
6 minconfiguration-as-code 2147.v8a_8d38668c72Requires Jenkins ≥ 2.541.1★★★★★
Learning goals
  • Explain JCasC's input (CASC_JENKINS_CONFIG the file / directory / URL it points to), when it runs (SYSTEM_CONFIG_LOADED after SYSTEM_CONFIG_ADAPTED and before config.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.
Prerequisites: Lesson 1 installation wizard, YAML basics. Importance:★★★★★ (foundation for all later modules)

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 elementWhat it controlsCorresponding action in the Lesson 1 wizard
jenkinssecurityRealm, authorizationStrategy, nodes, clouds, numExecutors, systemMessage, globalNodeProperties…“Create the first admin user”, add agent1
credentialssystem-level credentials (domainCredentials)Add gitea-myapp
securityGlobal 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
toolTool installations such as Git, JDK, MavenTools page
unclassifiedGlobal configuration of other plugins: location (Jenkins URL),globalLibraries,prometheusConfiguration,openTelemetry…Jenkins URL in “Instance configuration”
jobsProvided 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.xml history.
  • 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

  1. At startup: the plugin's ConfigurationAsCode.init() annotated @Initializer(after = SYSTEM_CONFIG_LOADED, before = SYSTEM_CONFIG_ADAPTED)— that is, Jenkins first loads the config.xml from disk, then JCasC uses the YAML to override the parts it declares.
  2. 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 reports Found conflicting configuration at …; lists are concatenated.
  3. Resolve variables: ${VAR} Passed to SecretSources to resolve in order (environment variables,/run/secrets/VAR files, optional Vault, etc.), supporting ${VAR:-default},${readFile:/path},${base64:…},${json:key:${VAR}},${trim:…}; literal ${…} use ^${…} escaping.
  4. Configurator: each root element has a RootElementConfigurator; it maps YAML keys to Java classes by @Symbol or class name (for example local → built-in user database,globalMatrix → Matrix authorization strategy), via @DataBoundConstructor/@DataBoundSetter constructs the object, then calls the corresponding setters and save() saves to disk.
  5. 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) reports No configurator found for the following root element: ….
  6. Runtime reload: Manage Jenkins → Configuration as Code → Reload existing configuration; or the CLI reload-jcasc-configuration; or set CASC_RELOAD_TOKEN then 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-cli or Helm's installPlugins); it does not store build history; it does not define jobs itself (leave that to jobs: + Job DSL).

Comparison with similar approaches

JCasC YAMLinit.groovy.d/*.groovyManual UI + backing up config.xmlGitHub Actions / Azure Pipelines
ExpressionDeclarative; key names come from the plugin's data bindingImperative Groovy, calling internal APIsNone (relies on people)SaaS platform, no server to configure
IdempotenceNaturally idempotent, can be applied repeatedlyMust be ensured manually——
ValidatableSchema,check-configurationCan only be tried by running itNo—
RiskYAML must be upgraded in step when a plugin renames a fieldBreaks when internal APIs change; scripts have full permissionsDrift, not rebuildable—
Common misconceptions① “With JCasC you don't need backups” — JCasC only covers configuration; build history, the credential encryption key (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

YAML sources CASC_JENKINS_CONFIG= /var/jenkins_home/casc_configs 01-system.yaml 02-security.yaml · 03-credentials.yaml (file / directory / URL) SecretSource Environment variables /run/secrets/<KEY> (Docker/K8s) Vault · Azure Key Vault AWS Secrets Manager / SSM configuration-as-code plugin ① Merge (errorOnConflict) ② Variable resolution ${…} ③ RootElementConfigurator dispatch ④ Construct objects by @Symbol / validate fields ⑤ Call setters and save() Jenkins controller In-memory objects: Jenkins.get() securityRealm / authorizationStrategy nodes / clouds / global plugin configuration JENKINS_HOME disk config.xml credentials.xml (encrypted with secrets/) nodes/agent1/config.xml org.jenkinsci.plugins…xml jobs/ (generated by jobs: + Job DSL)
Figure 1-1 JCasC is a converter from “YAML → Java objects → XML on disk”; it does not replace JENKINS_HOME, but drives the configuration files within it

Flowchart: Jenkins startup milestones and where JCasC fits

PLUGINS_STARTED EXTENSIONS_AUGMENTED SYSTEM_CONFIG_LOADED JCasC init()Merge → resolve → applyfailure = startup failure SYSTEM_CONFIG_ADAPTED JOB_LOADED COMPLETED First read config.xml from disk YAML overrides the parts declared in it Runtime reload (UI / CLI / POST /reload-configuration-as-code/) repeats “merge → resolve → apply” without restarting the JVM
Figure 1-2 JCasC runs after SYSTEM_CONFIG_LOADED; if the YAML has errors, Jenkins fails to start (ConfigurationAsCodeBootFailure), which is a good thing: failures are caught early

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.

Container environmentCASC_JENKINS_CONFIG casc_configs/jenkins.yaml(read-only mount) /run/secrets/JENKINS_ADMIN_PASSWORD Jenkins startupInitMilestone sequence Merge + resolveYamlUtils.mergeSecretSourceResolver Root configurators jenkins: credentials: unclassified: jobs: (job-dsl) Jenkins object modelHudsonPrivateSecurityRealm(admin)GlobalMatrixAuthorizationStrategyDumbSlave(agent1) · UsernamePassword(gitea-myapp) JENKINS_HOMEconfig.xml · users/admin_*/config.xmlnodes/agent1/config.xmlcredentials.xml (AES, key in secrets/)
Ready: container created, but Jenkins has not started yet.
$ docker run -d --name jenkins-casc ... jenkins-casc:2.580.2

Core commands and entry points

Command / entry pointPurposeKey points
CASC_JENKINS_CONFIGSpecify YAML sourcescomma-separated; directories read recursively; if unset, reads $JENKINS_HOME/jenkins.yaml
-Djenkins.install.runSetupWizard=falseSkip the install wizardPlace it in JAVA_OPTS; if not set, the wizard still asks for initialAdminPassword
jenkins-plugin-cli --plugin-file plugins.txtInstall plugins at image build time (JCasC does not install plugins)one per line id:version; dependencies are resolved automatically
Manage Jenkins → Configuration as CodeView / Download Configuration, Reload, Documentation (Reference)Use exported YAML as a “field dictionary”; do not commit it as-is
JENKINS_URL/configuration-as-code/schemaJSON Schema for the current instance's plugin combinationcan be used for completion / validation in the VS Code YAML extension
CLI: check-configuration / apply-configuration / export-configuration / reload-jcasc-configurationvalidate / apply / export / reloadRequires 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.

Prepare the directory, plugin list, and secret files
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/' >> .gitignore
Write jenkins.yaml (go through the wizard item by item)
jenkins:
  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: false
Build the image with plugins
FROM 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
Start (on the same network as Compose's gitea, to make Module 2 easier)
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.

Verification: no wizard, the admin can log in, configuration is all in
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.”

Experience drift correction: in the UI, change System Message to any text, save, then reload:
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.

Cleanup (optional): Module 2 will still use this instance, so keep it for now. Full cleanup:
docker rm -f jenkins-casc && docker volume rm jenkins_casc_home
Security noticesecrets/ 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).

Command-line operation questions
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}.

Scenario analysis questions
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):

▶
Learn Jenkins! Complete Jenkins Course - Zero to Hero — DevOps Journey
English · comprehensive course · for reviewing basic concepts such as installation, jobs, and agents

Official docs

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.

Shot 1 · 0–15s
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.
Shot 2 · 15–40s
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.
Shot 3 · 40–65s
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.
Shot 4 · 65–90s
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.
or score ≥ 70% on the quiz

Module 2 · Job DSL and Seed Jobs

06:00 – 13:00 · JCasC manages “what Jenkins looks like”; Job DSL manages “which jobs exist in Jenkins”
7 minjob-dsl 3732.v9a_c49a_61a_313JCasC jobs: root element★★★★☆
Learning goals
  • 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 jobDsl steps that generate, update, and delete other jobs; master removedJobAction,lookupStrategy,ignoreExisting.
  • Understand Job DSL script security (script approval and sandbox), and that inside JCasC jobs: must be written as ${} in ^${}.
Prerequisites: Module 1; Lesson 2's Jenkinsfile and multibranch pipelines. Importance:★★★★☆

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 jobDsl step 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

  1. The seed job checks out the DSL repo (such as lab/jenkins-jobs),jobDsl targets: 'jobs/**/*.groovy' and reads the script.
  2. The plugin executes the DSL in Groovy (under script security control); each pipelineJob(...) call builds an XML node tree.
  3. JobManagement For each job: if it does not exist, create it; if it exists, compare and update its config.xml (ignoreExisting: true when set, skipping existing ones).
  4. 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 removedJobAction the policy: IGNORE (default) / DISABLE / DELETE.
  5. lookupStrategy: JENKINS_ROOT (default, names relative to the root directory) or SEED_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

ApproachSuited forNotes
JCasC jobs:A few “bootstrap jobs”: folders, the seed job itself, platform jobsScripts embedded in YAML; Groovy's ${} must be written as ^${}; every JCasC reload re-executes it
Seed job + DSL repoMany business jobs, team self-servicerequires 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 DSLJenkins Job Builder (YAML, OpenStack)GitHub Actions / Azure Pipelines
Where definedGroovy running inside JenkinsExternal Python tool calling the REST APIYAML per repository; platform auto-discovers
CoverageAlmost all plugins (including dynamic DSL)Depends on JJB's own plugin support—
Deletion handlingremovedJobActionNeeds extra scriptsJust delete the YAML
Common misconceptions① “Job DSL and Pipeline are the same thing” — Job DSL generates jobs, while Pipeline (Jenkinsfile) describes what the job does at runtime; a common combination is DSL generating multibranch jobs, which read the Jenkinsfile in the repo. ② “Delete a job from the DSL and it disappears from Jenkins” — by default 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

jenkins.yamljobs:- folder('platform')- pipelineJob('platform/seed') Gitea: lab/jenkins-jobsJenkinsfile (jobDsl step)jobs/myapp.groovyjobs/nightly.groovy start / reload platform/seed (pipeline) ① checkout on agent ② jobDsl targets: 'jobs/**/*.groovy' ③ Script security: approve or sandbox ④ createOrUpdateConfig() ⑤ Compare with previous Generated Items ⑥ removedJobAction IGNORE / DISABLE / DELETE Generated items myapp/ (folder) myapp/myapp (multibranch → reads Jenkinsfile) myapp/nightly-scan (pipelineJob) legacy-build (removed from DSL → DELETE)
Figure 2-1 JCasC only “bootstraps” the seed job; business jobs are generated by the seed job from the DSL repo

Data flow: what happens to items during a seed run

Declared in DSLpipelineJob('x') x does not exist → create x exists → overwrite config.xml(skipped with ignoreExisting) Generated last run, not declared this timey (for example, a retired service) IGNORE: keep (default) DISABLE: disable but keep history DELETE: delete along with build history
Figure 2-2 The DSL is the “desired state”; the seed job converges the actual state toward it. DELETE is irreversible, so in production DISABLE is often used first to observe one cycle.

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.

Jobs declared in jobs/*.groovy of the DSL repo
removedJobAction:
Items in Jenkins (Generated Items records)
Initial state: Jenkins only has the platform/seed created by JCasC.
Started by user Lab Admin

Core commands and DSL snippets

Command / locationPurposeKey parameters / notes
jobDsl Pipeline stepRun DSL in a seed pipelinetargets,scriptText,removedJobAction,removedViewAction,lookupStrategy,sandbox,ignoreExisting,failOnMissingPlugin
JENKINS_URL/plugin/job-dsl/api-viewer/index.htmlDSL 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 / urlRun DSL at startup / reloadIn Groovy, the ${} is written as ^${}
JCasC security.globalJobDslSecurityConfiguration.useScriptSecurityMaster switch for Job DSL script securityDefault true; consider disabling only if the DSL repo is writable by administrators only
Manage Jenkins → In-process Script ApprovalApprove DSL scriptsRe-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).

Let agent1 connect to the 8082 instance (the same inbound agent as Lesson 1; connects over TCP 50000 within the Docker network, without exposing a port to the host):
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.

Create the DSL repo in Gitea 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
Migrate the root-level job from Lesson 1 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
Bootstrap the seed job in JCasC: add the file 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
About useScriptSecurity: false Once turned off, anyone who can modify the DSL repo can run arbitrary Groovy on the controller as SYSTEM. Only do this when the DSL repo has a protected branch and only platform administrators can merge; otherwise keep the default true, and use “administrator approval” or “sandbox + Authorize Project to run as a specified user”.
Run the seed job and check the results
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).

Experience removedJobAction: from 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'}
Cleanup:
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('…').

Command-line operation questions
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
Scenario analysis questions
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

▶
Continuous Delivery: Pipeline As Code With Jenkins — Eclipse Foundation
English · conference talk · the motivation and approach for “pipelines and jobs as code” (recorded earlier; plugin details follow this lesson)

No verified video was found that specifically demonstrates Job DSL seed jobs.

Official docs

Video storyboard (about 80 seconds)

This courseware cannot directly generate video/MP3, but storyboards and narration scripts are provided.

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–80s
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.
or score ≥ 70% on the quiz

Module 3 · Shared Libraries: reusing pipelines

13:00 – 21:00 · Consolidate the nearly identical Jenkinsfiles from 30 repositories into one versioned, testable library
8 minpipeline-groovy-lib 822.vc95f70dea_db_7Global library = trusted code★★★★★
Learning goals
  • 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') _,library steps, 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.
Prerequisites: Lesson 2's Declarative Pipeline and the CPS execution model. Importance:★★★★★

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.1 tags; critical services pin their versions, while other services follow main.
  • “Paved road”: business repos' Jenkinsfiles shrink to two or three lines, and the platform team is responsible for pipeline quality.

How: loading mechanism

  1. When the pipeline compiles the Jenkinsfile,LibraryDecorator finds @Library annotation (or at runtime encounters library step).
  2. LibraryAdder it 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 reports Could not find any definition of libraries [...].
  3. Version: if none is written @version use defaultVersion; if one is written but allowVersionOverride=false reports Version override not permitted for library ….
  4. The retriever (usually Modern SCM → Git) checks that version out into the libs/ (caching can be enabled); if there is no src nor vars it reports Library … expected to contain at least one of src or vars directories.
  5. src/ Added to the classpath; vars/*.groovy each file in it becomes a global variable (the file name is the variable name,call method lets it be called like a step).
  6. 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 throws RejectedAccessException.
  7. Library code, like the Jenkinsfile, follows the CPS rules (Lesson 2): it is interpreted on the controller,sh while steps are sent to the agent; classes must implement Serializable, and non-CPS methods use @NonCPS.

When: what belongs in the library

Put in the libraryKeep in the JenkinsfileDo not put in the library
Standard stages (test, build, scan, release), notifications, version calculation, Pod templatesService-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 LibraryGitHub Actions reusable workflows / composite actionsAzure Pipelines templates (extends/template)
LanguageGroovy (CPS)YAML + actions in any languageYAML template expressions
Version reference@Library('lib@v1.0')uses: org/repo/.github/workflows/x.yml@v1resources.repositories + ref
Enforced useImplicit loading (implicit) only makes the library “automatically available”; it cannot enforce useOrganization-level required workflows / rulesetsextends + required template checks

For comparison:GitHub course 's reusable workflows,Azure DevOps course 's templates.

Common misconceptions① “Library code runs on the agent” — the library's Groovy runs on the controller; only 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

lab/myappJenkinsfile (2 lines)@Library('lab-shared@v1.0') _myappPipeline(imageName: 'myapp') lab/jenkins-shared-libtags: v1.0, v1.1vars/ src/ resources/Protected branch + CODEOWNERS controller (CPS VM) Compile Jenkinsfile → find @Library Resolve library config (folder → global untrusted → global trusted) Git checkout v1.0 to builds/N/libs/… src → classpath; vars → global variablesTrusted: no sandbox / untrusted: sandbox agentonly runs sh / junit collectionpytest, docker build(library Groovy does not run here) steps
Figure 3-1 The library is compiled and interpreted on the controller; the agent only receives concrete steps

Version strategy: who uses which version

v1.0 v1.1 main (unreleased) Payment service: pinned to v1.0 defaultVersion = v1.1 Library's own PR builds:@Library('lab-shared@main') When allowVersionOverride=true, the Jenkinsfile can override defaultVersion with @version; optional “Fresh clone per build” and cache settings
Figure 3-2 Publish the library with Git tags; the default version only moves forward after validation, and critical services pin explicitly

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 configuration location: Version requested by Jenkinsfile:
CompileLibraryDecorator Find configLibraryResolver Resolve versiondefault / override Check outSCMSourceRetriever Loadsrc / vars ExecutemyappPipeline()
Select a configuration, then click Play.
Started by an SCM change

Library code and invocation

SyntaxPurposeNotes
@Library('lab-shared@v1.0') _Load at compile timeat 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 runtimea 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 ReferenceView vars/*.txt helpLocated on any pipeline job page
ReplayTemporarily modify the library code and re-run a buildFor 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.

Create the library repo and push the v1.0 tag
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
Register the global trusted library on the 8080 instance: Manage Jenkins → System → Global Trusted Pipeline Libraries → Add: Name 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.)
Modify myapp's Jenkinsfile and push
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 main
Observe the build log (on the job myapp 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
Experience version pinning: modify on the library's main 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.)
(Optional) Debug with Replay: on a myapp build page, click Replay to temporarily edit vars/pytestStage.groovy contents and re-run once, without affecting the repo.
Cleanup / rollback: to restore the Lesson 2 Jenkinsfile if needed: git mv -f Jenkinsfile.hour2.bak Jenkinsfile && git commit -m revert && git push. Later modules keep the library version by default.
Unit-testing the library commonly used in the community JenkinsPipelineUnit Test with JUnit/Spock without starting Jenkins 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.

Command-line operation questions
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"
Scenario analysis questions
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

▶
Complete Jenkins Pipeline Tutorial | Jenkinsfile explained — TechWorld with Nana
English · Jenkinsfile structure, parameters, external Groovy scripts; can serve as prerequisite review for shared libraries (the video itself does not specifically cover Shared Libraries)

No video verified via oEmbed that specifically covers Shared Libraries was found.

Official docs

Video storyboard (about 90 seconds)

This courseware cannot directly generate video/MP3, but storyboards and narration scripts are provided.

Shot 1 · 0–20s
Visual: 30 nearly identical Jenkinsfiles laid out side by side, with the differences flashing red.
Narration: copy-pasted pipelines fork sooner or later.
Shot 2 · 20–50s
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.
Shot 3 · 50–75s
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.
Shot 4 · 75–90s
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.
or score ≥ 70% on the quiz

Module 4 · Running Jenkins on Kubernetes with Helm

21:00 – 28:00 · Official jenkinsci chart: one values file = plugin list + JCasC + persistence + RBAC
7 minchart jenkins 5.13.3 · appVersion 2.580.2kind cluster lab · namespace jenkins · release jenkins★★★★★
Learning goals
  • Use helm upgrade --install jenkins jenkins/jenkins -n jenkins -f values-lab.yaml to deploy the controller, and read the generated StatefulSet jenkins, Service jenkins/jenkins-agent, PVC, ServiceAccount, and Role.
  • Understand the chart's three configuration channels: installPlugins/additionalPlugins (init container init installs plugins),JCasC.configScripts (ConfigMap + config-reload sidecar 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.
Prerequisites:Helm course(values, upgrade, rollback);K8s course(StatefulSet, PVC). Importance:★★★★★

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/RoleBindinglets 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

  1. Plugins: controller.installPlugins + additionalPlugins written to the list in the ConfigMap plugins.txt; the init container init runs apply_config.sh, calling jenkins-plugin-cli to download plugins. Changing the plugin list changes the Pod template's checksum/config annotation → the StatefulSet rolling-restarts the controller.
  2. JCasC: the chart ships a default configuration (security realm, authorization, Kubernetes cloud,location etc.); your controller.JCasC.configScripts.<name> each entry generates a labeled ConfigMap. config-reload The sidecar (kiwigrid/k8s-sidecar 2.14.3) watches these ConfigMaps, writes into /var/jenkins_home/casc_configs/, then calls http://localhost:8080/reload-configuration-as-code/?casc-reload-token=$(POD_NAME)——without restarting the Pod.
  3. Secrets: controller.additionalExistingSecrets Mount a key from an existing Secret, and reference it in JCasC as ${<secret name>-<key name>} ; the administrator account uses controller.admin.existingSecret.

When: trade-offs in production

  • Plugins: OK for labs installPlugins; production recommends a custom-built image (Dockerfile + jenkins-plugin-cli) and set installPlugins: false, so startup does not depend on the update center, images can be scanned, and rollback only requires switching the tag. controller.initializeOnce: true This 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 use controller.ingress or the chart's newly added controller.httpRoute (Gateway API).

Comparison with other deployment methods

Helm chart (this lesson)Docker Compose (Lesson 1)Jenkins OperatorCloudBees CI (commercial)
Configurationvalues + JCasCcompose.yaml + manual / JCasCCRDCasC bundles + operations center
agentKubernetes plugin Podsfixed-container agent1PodPods, centrally managed
Suited formost self-hosted teamssingle machine / labDepends on project status; check its repository activity before choosinglarge scale, needs vendor support
Common misconceptions① “A helm upgrade that changes JCasC always restarts Jenkins” — if only 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

kind cluster lab · namespace jenkins Service jenkins:8080 ← port-forward 8081 Service jenkins-agent:50000 (inbound TCP) Pod jenkins-0 (StatefulSet jenkins) init: config-reload-initfirst copy of JCasC files init: initapply_config.sh → install plugins container jenkinsCASC_JENKINS_CONFIG=/var/jenkins_home/casc_configs/run/secrets/additional/* config-reloadwatch ConfigMap→ write files→ POST reload ConfigMapsjenkins-jenkins-config-* Secretsjenkins-admin · jenkins-casc-secrets PVC jenkins → PVlocal-path (kind) ServiceAccount jenkins + Role (pods, pods/exec, pods/log, events) → Module 5 creates agent Pods
Figure 4-1 Main objects generated by the chart; configuration is provided by ConfigMap/Secret, and state lives on the PVC

Flowchart: two different paths for taking effect after helm upgrade

helm upgrade Only configScripts changedConfigMap content changes config-reload detects the changewrite file + POST reload JCasC reloadPod does not restart, builds are not interrupted Changing plugins / image / javaOptsPod template (checksum) changes StatefulSet deletes jenkins-0stops per terminationGracePeriod Pod is recreated, init runs againrunning builds may be interrupted
Figure 4-2 First use helm diff or helm template to determine which path a change belongs to; when a restart is needed, enter quiet-down mode first

Animation: 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.

Ready: values-lab.yaml is written, and namespace jenkins is empty.
$ helm upgrade --install jenkins jenkins/jenkins -n jenkins -f values-lab.yaml --version 5.13.3

Core commands

CommandPurposeKey parameters
helm show values jenkins/jenkins --version 5.13.3View 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.3Install or upgradepin --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:8080Access the UI locally8080 is already used by the Lesson 1 Compose instance, so use 8081
kubectl -n jenkins logs jenkins-0 -c init / -c config-reloadPlugin install log / hot-reload logPreferred for troubleshooting
helm rollback jenkins <REV> -n jenkinsRoll back the releaseRolls 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)

Create secrets (not in Git)
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
Save values and preview: copy the 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.

Install
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
View plugin installation and JCasC logs
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
Log in and verify
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"}]}
Experience hot reload: change in values 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.

(Optional) Run the seed job: 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’.
Cost, permissions, risks, and cleanup: no cloud cost; requires kind cluster admin permissions. Risk: 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.

Command-line operation questions
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"]'
Scenario analysis questions
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:

▶
How to Use Kubernetes Pods As Jenkins Agents — CloudBeesTV
English · Kubernetes cloud and Pod template configuration (the plugin UI may differ slightly from the current version)

Official docs

Video storyboard (about 90 seconds)

This courseware cannot directly generate video/MP3, but storyboards and narration scripts are provided.

Shot 1 · 0–20s
Visual: one values file split into three colored blocks: plugins, JCasC, secrets.
Narration: the official Helm chart splits Jenkins configuration into three channels.
Shot 2 · 20–50s
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.
Shot 3 · 50–75s
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.
Shot 4 · 75–90s
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.
or score ≥ 70% on the quiz

Module 5 · Kubernetes plugin: dynamic Pod agents

28:00 – 35:00 · As soon as a build enters the queue, a dedicated Pod is created for it; when the build ends, the Pod disappears
7 minkubernetes 4560.vc25b_83890c34Requires Jenkins ≥ 2.516.3★★★★★
Learning goals
  • 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 → container steps run via the exec API → delete the Pod.
  • Be proficient in writing agent { kubernetes { yaml … ; defaultContainer … } } and scripted podTemplate / 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).
Prerequisites: Module 4; Lesson 1's “queue → label matching → executor”. Importance:★★★★★

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 containerCap limits;
  • 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

  1. 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 ‘…’”.
  2. 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).
  3. Create Pod: the plugin registers a node in Jenkins KubernetesSlave node (offline), merges the template (inherits inheritFrom, YAML merge strategy), and automatically injects jnlp container and environment variables (JENKINS_URL,JENKINS_SECRET,JENKINS_AGENT_NAME,JENKINS_TUNNEL etc.), and uses the ServiceAccount token to send a request to kube-apiserver to POST /api/v1/namespaces/jenkins/pods.
  4. 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.
  5. 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.
  6. Execute: the queue assigns the build to an executor on that node. container('python') (or defaultContainer) steps inside the sh is 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.
  7. 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

ScenarioRecommendation
Testing and building for Python/Node/Go/JavaIdeal; for dependency caching use a PVC (persistentVolumeClaim volume) or an artifact repository proxy
Building container images inside a PodAvoid 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/macOSGPU and Windows nodes can be targeted via nodeSelector/tolerations; macOS can only use static agents
Extremely short tasks (a few seconds) in very large volumePod 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 agentStatic agent (Lesson 1 agent1)GitHub Actions ARC / Azure Pipelines self-hosted agent on K8s
LifecycleCreated per build, deleted when finishedLong-runningARC: runner Pods scale on demand
Toolchaineach pipeline chooses its own imagepre-installed on the agentrunner image + container jobs
State pollutionNoneYes (requires regular cleanup)Depends on configuration
Common misconceptions① “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

jenkins-0 (controller) Queue: myapp/k8s-pytest #3 NodeProvisioner → KubernetesCloud "kubernetes" fabric8 client (SA jenkins token) Agent listener: Service jenkins-agent:50000or WebSocket: Service jenkins:8080 kube-apiserverRBAC: Rolejenkins-schedule-agents POST pods Pod myapp-k8s-pytest-3-xxxxx jnlp (inbound-agent)remoting · JENKINS_SECRET python (python:3.13-slim)command: sleep infinity emptyDir workspace/home/jenkins/agentshared by both containers Scheduling + startup ① Connect back to controller ② sh → exec API into the python container
Figure 5-1 The controller creates the Pod via the API; the jnlp container in the Pod connects back actively; steps run in the tool container via the exec API

Sequence diagram: Pod agent lifecycle for one build

QueueK8s pluginapiserverkubeletjnlp container needs label X create Pod bind → node watch pull images, start containers remoting handshake (secret) → node online executor available pods/exec (sh) build complete delete Pod (podRetention Never)
Figure 5-2 Queue wait time = provisioning decision + scheduling + image pull + container start + connect-back; Lesson 7 uses this diagram to analyze “builds stuck in the queue”

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.

Fault injection:
Queuek8s-pytest #3 NodeProvisioner→ KubernetesCloud kube-apiserverRBAC · admission · etcd schedulerbind → lab-worker2 kubelet / CRIpull images · start containers agent Pod jnlp python controlleragent listenerexecutorconsole log Queued 0 s
Ready: a developer pushed a commit, and the multibranch scan triggered myapp/k8s-pytest #3.
Started by an SCM change

Pipeline syntax and parameters

Syntax / parameterPurposeNotes
agent { kubernetes { yaml '''…'''; defaultContainer 'python' } }Declarative: generate Pod for this pipelineAlso can yamlFile 'ci/pod.yaml' (read from the repo),inheritFrom 'default'
podTemplate(yaml: …) { node(POD_LABEL) { container('python') { … } } }Scripted: define the template explicitlyPOD_LABEL is the unique label generated by the plugin
container('name') { sh … }run steps in a specified containerIf unspecified, runs in the jnlp container (or defaultContainer)
cloud: containerCapStrmaximum number of agent Pods this Cloud can have at the same timechart value agent.containerCap (default 10)
templates: instanceCap,idleMinutes,podRetentionper-template limit / idle retention / whether to keep the Pod after failureFor debugging, you can temporarily set podRetention: onFailure
chart: agent.websocket,agent.directConnectionconnection methoddefault TCP (jenkinsTunnel = jenkins-agent:50000)
showRawYamlwhether to print the Pod YAML in the consoleconsider 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)

Add a label to the default Pod template 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.

Run the seed job (now that there is a 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).

Add a job definition for the Kubernetes pipeline: in 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')
    }
  }
}
In the myapp repo, add 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
Prove that sh goes through the exec API: view the Pod and containers while the build runs:
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.

(Optional) Create a failure: change the image to 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.
Cleanup: agent Pods are deleted automatically; confirm nothing is left over: 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.

Command-line operation questions
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
Scenario analysis questions
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

▶
How to Use Kubernetes Pods As Jenkins Agents — CloudBeesTV
English · configuring a Kubernetes cloud and Pod templates and using them in pipelines (the UI and version may be outdated; this lesson takes precedence)

Official docs

Video storyboard (about 100 seconds)

This courseware cannot directly generate video/MP3, but storyboards and narration scripts are provided.

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–70s
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.
Shot 4 · 70–100s
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.
or score ≥ 70% on the quiz

Module 6 · Backup, restore, and upgrade strategy

35:00 – 42:00 · Configuration lives in Git, state lives in JENKINS_HOME; both must be restorable, and you must be able to roll back before upgrading
7 minLTS 2.580.2 · Java 21/25thinBackup 2.1.5★★★★★
Learning goals
  • 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/ and credentials.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.
Prerequisites: Modules 1 and 4. Importance:★★★★★

What: what exactly needs protecting

Contents of JENKINS_HOMERoleRebuildable from Git?Backup recommendation
config.xml,*.xml (global plugin configuration),nodes/system configuration✓ (JCasC)Still recommended to back up, for faster recovery
jobs/*/config.xmlJob 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 tokenspartially (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

MethodConsistencyRPO / RTOSuitable for
CSI VolumeSnapshot (such as AKS Azure Disk snapshots)crash-consistent (better after quiet-down)minutes / minutesproduction preferred; kind's local-path does not support snapshots
File-level tar (kubectl exec … tar)file-level; files of running builds may be inconsistentdepends on the scheduled jobsmall instances, drills, migration
thinBackup plugin (2.1.5)can wait for idle / force quiet modefull + incremental by cronback up to a second volume, then sync externally to object storage
VeleroK8s objects + volumes (snapshot or filesystem backup)On schedulewhole-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-configuration validate 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.

Common misconceptions① “Backing up the whole JENKINS_HOME is the safest” — including workspace and caches makes the backup several times larger, slows restores, and adds no value. ② “Helm rollback is a Jenkins rollback” — it only rolls back Kubernetes objects (image tag, ConfigMap); the data on the volume has already been modified by the new version. ③ “You can click Update all on plugins at any time” — there are dependencies and data migrations between plugins and between plugins and core, so validate in staging first; production instances should ideally not be upgraded directly in the UI (plugins come from the image).

Architecture diagram: the recovery model of “configuration in Git, state on volumes”

Git (configuration)values-lab.yaml + JCasClab/jenkins-jobs (Job DSL)lab/jenkins-shared-lib (v1.x)plugins.txt / image tag Key custody (separate from backups)Key Vault / Secrets Managercopy of JENKINS_HOME/secrets/jenkins-admin · jenkins-casc-secrets PVC jenkins (state)jobs/*/builds/ · fingerprints/credentials.xml · users/secrets/ (encryption keys)Exclude: workspace/ caches/ war/plugins/ (rebuildable) VolumeSnapshot (production)daily + before upgrades tar / thinBackup → object storageencrypted, off-site, keep N copies Restore drill (quarterly)verify RTO in a staging namespace Rebuild
Figure 6-1 Configuration is rebuilt from Git, state is restored from volume backups, and keys are stored separately

Flowchart: one LTS upgrade (2.568.3 → 2.580.2)

Read the upgrade guideand security advisories Staging: restorea production backup Upgrade image +compatible plugins check-config+ smoke test Production: snapshot+ quiet-down Upgrade Verify +resume scheduling Failure → restore the pre-upgrade snapshot + old image tag (rolling back the image alone is not enough)
Figure 6-2 Each upgrade step can return to the previous step; a usable snapshot must exist before the last step

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).

Select a backup scope.
$ tar -C /var/jenkins_home -czf backup.tgz ...

Core commands

CommandPurposeNotes
quiet-down / cancel-quiet-down (CLI)Stop accepting new builds / resumewaits for running builds to finish; can take -block -timeout
kubectl exec jenkins-0 -c jenkins -- tar … | gzipfile-level backup streamed to localDo not add -t (it corrupts the binary stream)
helm upgrade … --set controller.replicas=0Maintenance mode: stop the controller, keep the PVCthe chart supports replicas set to 0
kubectl get volumesnapshotCSI snapshotrequires a CSI driver and VolumeSnapshotClass (supported on AKS; not supported by default on kind)
curl …/updateCenter/ / security warnings in Manage JenkinsView plugin security advisoriessubscribe 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)

Risk notice This lab will delete the Jenkins release and PVC in kind. Only run this in the lab environment; first confirm that the backup file from step 1 has a reasonable size and can be listed secrets/.
Record the baseline and back up
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.tgz
Simulate disaster: uninstall the release (the PVC is deleted with it)
helm 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).

Reinstall in maintenance mode (create only the PVC and other objects; do not start the controller)
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.

Use a temporary Pod to write the backup back to the PVC
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
Start the controller and verify
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.

Counterexample to consider (no need to run): if the backup is missing 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.
Cleanup: keep the backup file (Lessons 6 and 7 also use this instance). 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.

Command-line operation questions
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"
Scenario analysis questions
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

Video storyboard (about 90 seconds)

This courseware cannot directly generate video/MP3, but storyboards and narration scripts are provided.

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–70s
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.
Shot 4 · 70–90s
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.
or score ≥ 70% on the quiz

Module 7 · Monitoring Jenkins: metrics, logs, and alerts

42:00 – 50:00 · Alerts fire before developers complain that “builds are stuck”
8 minprometheus 873.v054598e6e84dopentelemetry 3.1605.v37c3e29857e5★★★★☆
Learning goals
  • 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 (release kps, namespace monitoring).
  • Write Jenkins' core alerts (unavailability, queue backlog, build failure rate, disk), and understand how the OpenTelemetry plugin turns each build into a trace.
Prerequisites: ServiceMonitor, PromQL, and Alertmanager basics from the Prometheus course. Importance:★★★★☆

What: what observability data Jenkins can output

SignalSourceTypical 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 pluginone 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 metricskube-state-metrics, kubelet/cAdvisorcontroller Pod restarts, memory, PVC free space, number of Pending agent Pods
LogsContainer 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

  1. The plugin computes metrics in the background at collectingMetricsPeriodInSeconds (default 120 seconds; can be overridden with the environment variable COLLECTING_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.
  2. The metric name prefix is determined by the “default namespace”, whose default value is default, so the names are default_jenkins_executors_queue_length,default_jenkins_builds_duration_milliseconds_summary,default_jenkins_up etc.; the job name is placed in the label jenkins_job .
  3. Default endpoint requires no authentication (useAuthenticatedEndpoint=false); once enabled, it requires Metrics/View permission, and Prometheus must scrape with credentials. Inside the cluster, it is recommended to pair this with a NetworkPolicy that allows only Prometheus access.
  4. Set in the chart controller.prometheus.enabled: true to generate a ServiceMonitor (scraping the Service jenkins 's http port, path /prometheus, interval default 60s),alertingrules and 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

  1. controller availability + disk + memory (needed from day one);
  2. queue length / wait time (essential in a Pod agent environment);
  3. build failure rate and duration (dashboards for teams);
  4. traces (enable when investigating slow builds; watch the data volume).

Comparison with similar approaches

Prometheus pluginOpenTelemetry pluginGitHub Actions / Azure Pipelines
ModePull (scrape)Push (OTLP)Built-in platform statistics + API/Webhook export
StrengthsAlerting, capacity trendsDuration breakdown of a single buildNo need to self-host
CaveatsEnabling “per-build metrics” causes high cardinalitytrace volume grows with the number of buildslimited fine-grained metrics
Common misconceptions① “/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

namespace jenkins jenkins-0/prometheus/ (computed every 120s)OTel plugin → OTLP push ServiceMonitor jenkins PrometheusRule (alertingrules) namespace monitoring (release kps) Prometheus Operator: select by release: kpsServiceMonitor / PrometheusRule Prometheus: scrape + rule evaluation Alertmanager Grafana OTel Collector:4317 OTLP gRPCtraces → Tempo/Jaeger NotifyTeams / Slack / email OTLP push (traces + metrics)
Figure 7-1 Metrics are “pulled” and traces are “pushed”; the labels on ServiceMonitor and PrometheusRule must match kps's selectors

Data flow: from queue backlog to alert notification

Queue: 8 buildscontainerCap=6 Plugin computes≤120s delay scrapeevery 60s rule >3pending for 5mfiring Alertmanagergroup → notify End-to-end delay ≈ collection interval + scrape interval + for duration + Alertmanager group_wait
Figure 7-2 Alert latency is the sum of each stage; when setting for, consider the plugin's 120-second collection interval

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.

New builds per minute: 3 containerCap: 6
Real queue lengthMetric value (plugin cache)Alert firing
Rule state: inactive
t=0m

Configuration and queries

Location / commandPurposeNotes
curl http://127.0.0.1:8081/prometheus/View metrics directlyNote the trailing slash; no credentials are needed if authentication is not enabled
chart: controller.prometheus.enabled / serviceMonitorAdditionalLabels / alertingrules / alertingRulesAdditionalLabelsgenerates ServiceMonitor / PrometheusRulekps selects by default by release: kps label selection
JCasC: unclassified.prometheusConfigurationplugin settings (path, namespace, interval, authentication…)use the key names from this instance's JCasC Reference / export
JCasC: unclassified.openTelemetryOTLP endpoint, serviceNamefields 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)

Confirm kube-prometheus-stack (the Prometheus course already installed release in the kind cluster lab 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).

Enable the plugin and ServiceMonitor: after modifying values as in the “Commands” tab:
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.

View metrics directly
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.0
Confirm the target in Prometheus
kubectl -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).

Create a queue backlog: temporarily set 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.

Restore: sed -i 's/containerCap: 2/containerCap: 6/' values-lab.yaml then helm upgrade; after the queue clears, the alert resolves automatically.
(Optional) OpenTelemetry: if the OTel Collector + Tempo were deployed in the Prometheus course, add in values 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.

Command-line operation questions
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])))
Scenario analysis questions
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

▶
How to Monitor Jenkins With Grafana and Prometheus — CloudBeesTV
English · Prometheus metrics plugin + Grafana dashboards (versions may be older; metric names follow this lesson's verification)
▶
Monitoring Production grade Jenkins using Prometheus, Grafana & InfluxDB — Deekshith SN
English · production monitoring approach and query examples

Official docs

Video storyboard (about 80 seconds)

This courseware cannot directly generate video/MP3, but storyboards and narration scripts are provided.

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–65s
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.
Shot 4 · 65–80s
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.
or score ≥ 70% on the quiz

Module 8 · Hours 1–5 recap, self-check, and cleanup

50:00 – 60:00 · Tie the five hours into one line: how one commit passes through every layer of the Jenkins platform
10 minReused: kind lab · ns jenkins · release jenkins★★★★☆
Learning goals
  • 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.
Prerequisites: Modules 1–7. Importance:★★★★☆

What: what you built in the first five hours

LessonTopicAssets left behindPosition in a “build”
Lesson 1Core foundations: controller, agent, jobs, credentials~/jenkinslab Compose: jenkins / agent1 / gitea; credentials gitea-myappqueue → label matching → executor
Lesson 2Production readiness: Declarative Pipeline, multibranch, CPSmyapp's Jenkinsfile, multibranch jobthe pipeline is interpreted on the controller, and steps are sent to the agent
Lesson 3Azure: ACR, credentials to the cloudresource group rg-jenkins-lab (should already be cleaned up)build artifacts are pushed to a cloud registry and deployed
Lesson 4AWS: ECR, credentials to the cloudECR 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, monitoringkind lab release in jenkins; Gitea repositories lab/jenkins-jobs,lab/jenkins-shared-lib; values-lab.yaml; backup packagethe platform itself is rebuildable, scalable, and observable

Why: four questions of platform maturity

  1. Rebuildable: if you delete the controller, can you recover within 1 hour using only Git + backups? (JCasC, Job DSL, shared libraries, Helm, backups)
  2. Scalable: at peak, do builds automatically get resources? (Kubernetes plugin, containerCap, cluster scaling)
  3. Observable: are problems detected before users notice? (metrics, alerts, traces)
  4. 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

ConcernLessons 1–2 (Compose)Lesson 5 (kind + Helm)
ConfigurationInstall wizard + UIvalues + JCasC (ConfigMap hot reload)
JobsMultibranch jobs created in the UIJCasC bootstraps the seed job → Job DSL
Pipelinefull Jenkinsfile in every reposhared library + two-line Jenkinsfile
agentpersistent agent1 (Docker access)one Pod per build
DataDocker volume jenkins_homePVC jenkins + backups/snapshots
MonitoringNoneServiceMonitor + 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.

Common misconceptions“If everything is code, no documentation is needed” — you still need a one-page runbook: how to recover, how to upgrade, who has admin rights in an emergency, and the alert response process. Code describes “what it is”; the runbook describes “what to do when something goes wrong”.

Overview diagram: layers of the Jenkins platform

Git (Gitea lab/*)myapp (Jenkinsfile 2 lines) · jenkins-shared-lib (v1.x) · jenkins-jobs (Job DSL) · jenkins-config (values + JCasC) controller (release jenkins)JCasC: security · credentials · libraries · cloud · seed jobsJob DSL: myapp/*, platform/seedQueue · NodeProvisioner · CPS execution One-time Pod agentjnlp + python:3.13-slimsh via exec API · deleted after the buildcontainerCap / ResourceQuota State: PVC jenkinsbuilds · secrets/ · credentials.xml → snapshots/backups Observability: kps + OTel/prometheus/ → alerts; trace → wait/execution time kind cluster lab (Kubernetes v1.37) · namespaces jenkins / myapp / monitoring — Lessons 6 and 7 continue to use them
Figure 8-1 Every layer can be rebuilt from Git or backups

Timeline: capabilities accumulated over five hours

Lesson 1Can build Lesson 2Pipeline as code Lesson 3Deliver to Azure Lesson 4Deliver to AWS Lesson 5Platform as code
Figure 8-2 From “it runs” to “operable”

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.

A developer pushed a fix to the main branch of lab/myapp.
$ git push origin main

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

LevelCommandImpact
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=0controller stopped, PVC kept
C. Delete Jenkinshelm uninstall jenkins -n jenkins; kubectl delete ns jenkinsPVC and data are deleted (back up first)
D. Clean up everythingkind 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)

Run the self-check script (“Commands” tab); all items should be OK. For any failed item, go back to the “Troubleshooting” tab of the corresponding module or the troubleshooting tree below.
Rebuildability check: answer the following three questions and verify —
  • Your values-lab.yaml has been committed to Gitea (for example lab/jenkins-config)? git -C ~/jenkinslab/k8s status
  • Secret jenkins-admin,jenkins-casc-secrets values are also stored safely elsewhere (not only in the cluster)?
  • Has the most recent backup been tar -tzf verified and includes secrets/?
(Optional, 15 minutes) Full rebuild drill: in another namespace 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.
Clean up at level A (see the “Commands” tab), and confirm:
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
Cost and risk review: this lesson has no cloud cost; if you use an Azure VM, stop the VM after class. Confirm the backup package,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
Command-line operation questions
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
Scenario analysis questions
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

▶
Jenkins Tutorial – How to Deploy a Test Server with Docker + Linux (Full Course) — freeCodeCamp.org
English · full course · reviews the basics of Lessons 1–2
▶
Learn Jenkins! Complete Jenkins Course - Zero to Hero — DevOps Journey
English · full course · review
▶
Run Jenkins in Docker Container - Jenkins Pipeline Tutorial for Beginners 1/4 — TechWorld with Nana
English · running Jenkins in Docker (corresponding to the Lesson 1 Compose environment)

Video storyboard (about 60 seconds)

This courseware cannot directly generate video/MP3, but storyboards and narration scripts are provided.

Shot 1 · 0–20s
Visual: five steps light up in turn, labeled with the five lesson topics.
Narration: five hours, from “it can build” to platform as code.
Shot 2 · 20–45s
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.
Shot 3 · 45–60s
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.
or score ≥ 70% on the quiz

Command cheat sheet

JCasC · Job DSL · Shared Library · Helm · Pod agent · Backup · Monitoring
After classVerified 2026-11-16

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.html

Shared 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 / credentialsId

Helm (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 -d

Pod 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 / resources

Backup 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.v054598e6e84d

Quick troubleshooting table

SymptomCheck firstCommon causes
controller exits right after startuplogs -c jenkins | grep -i cascinvalid JCasC field, the plugin for the root element is not installed, configuration conflict
jenkins-0 stuck in Initlogs -c initplugin download failure, plugin requires a higher core
JCasC change has no effectlogs -c config-reload, casc_configs contentConfigMap propagation delay, YAML error causing reload rejection, concurrent reload 409
builds stay queuedget pods -n jenkins, build consolelabel mismatch, containerCap full, Pod Pending, agent connect-back failure
No such DSL methodbuild log starts with Loading librarylibrary not loaded, file name casing
script not yet approvedIn-process Script ApprovalJob DSL script security
credentials invalid after restorels secrets/secrets/ not backed up or does not match
Prometheus has no targetServiceMonitor labelsmissing 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

Delete Jenkins, and fully recover it within 30 minutes using only Git and backups
about 30 minuteskind lab · ns jenkins

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.

Put the configuration into Git: create in Gitea 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
Back up and verify: quiet-down → tar (excluding regenerable directories) → cancel-quiet-down; tar -tzf confirm it includes secrets/master.key, and record the sha256.
Record the baseline: myapp/k8s-pytest 's lastBuild number,platform/seed the list of generated jobs (list-jobs myapp).
Create the disaster: helm uninstall jenkins -n jenkins, and confirm the PVC is deleted.
Rebuild from Git: in a new directory 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.
Verify functionality: run the “Module 8 self-check script”; trigger one myapp/k8s-pytest, the build number should continue after the baseline; observe Pod creation and deletion.
Verify observability: in Prometheus, default_jenkins_up == 1; trigger again with containerCap=2 + 8 builds JenkinsQueueBacklog, then restore.
Review: record the actual RTO (time from uninstall to the first successful build) and problems encountered, update the README runbook, and commit.

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

All version numbers were verified against official sources on 2026-11-16
Verified 2026-11-16
TopicVerification resultSource (accessed 2026-11-16)
Jenkins LTS / weeklyLTS 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 requirementSince 2.555.1, only Java 21 or Java 25 is supportedLTS changelog
2.580 upgrade guide2.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 notesupgrade-guide/2.580
Helm chartjenkins 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/jenkinshelm-charts releases, Chart.yaml, values.yaml, templates/*
Chart behaviorinit 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-agentscharts/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 mechanisminitialized 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 nameconfiguration-as-code-plugin(ConfigurationAsCode.java, yaml/*MergeStrategy.java, SecretSourceResolver.java, docs/features/secrets.adoc, configurationReload.md, demos/*)
Job DSLSteps jobDsl parameters; useScriptSecurity default true; the error message for sandbox needing a specified userjob-dsl-plugin(ExecuteDslScripts.java, GlobalJobDslSecurityConfiguration.groovy, Messages.properties); JCasC demos/jobs
Shared Library“Global Trusted Pipeline Libraries” and untrusted libraries; original error messagespipeline-groovy-lib-plugin(LibraryAdder, LibraryConfiguration, Messages.properties);Handbook
Prometheus plugindefault path prometheus, namespace default, job label jenkins_job, collection interval 120s, no authentication by default; metric name listprometheus-plugin(PrometheusConfiguration.java, docs/metrics/index.md, docs/configuration/configuration.md)
OpenTelemetry pluginJCasC 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 / Helmkind v0.33.0, kindest/node v1.37.0, Helm 4.3.x — reuses the facts already verified in this repository's Kubernetes and Helm coursesK8s course · Helm course
kube-prometheus-stackrelease kps, namespace monitoring, selector labels release: kps, Service kps-kube-prometheus-stack-prometheus — follows the Prometheus course conventionsPrometheus & 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 IDTitleChannelWhere used
ZXaorni-icgHow to Use Kubernetes Pods As Jenkins AgentsCloudBeesTVModules 4, 5
3H9eNIf9KZsHow to Monitor Jenkins With Grafana and PrometheusCloudBeesTVModule 7
AHSHksfg1BEMonitoring Production grade Jenkins using Prometheus, Grafana & InfluxDB | Monitoring With GrafanaDeekshith SNModule 7
7KCS70sCoK0Complete Jenkins Pipeline Tutorial | Jenkinsfile explainedTechWorld with NanaModule 3
ORNDwYXa4nQContinuous Delivery: Pipeline As Code With JenkinsEclipse FoundationModule 2
6YZvp2GwT0ALearn Jenkins! Complete Jenkins Course - Zero to HeroDevOps JourneyModules 1, 8
f4idgaq2VqAJenkins Tutorial – How to Deploy a Test Server with Docker + Linux (Full Course)freeCodeCamp.orgModule 8
pMO26j2OUMERun Jenkins in Docker Container - Jenkins Pipeline Tutorial for Beginners 1/4TechWorld with NanaModule 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,podRetention and 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 stable git branch 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-jdk21 and 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.