JENKINS
COMPLETE
Table of Contents
Jenkins
Picking up from Feedback, where the loop closed — we now implement that entire loop in Jenkins, starting with the topology that runs everything.
01 / Why Jenkins
- WHAT — open-source automation server: pipelines as code, 1,800+ plugins, controller + agents. Self-hosted, free, runs anywhere.
- WHY — your data/secrets on your infra; reaches air-gapped networks and special hardware; no per-minute billing.
- WITHOUT IT — releases from laptops: no audit trail, secrets in shell history, one person's memory as infrastructure.
02 / Concept Map
| Generic | Jenkins |
|---|---|
| Pipeline | Jenkinsfile |
| Runner | Agent + executors |
| Trigger | Webhook / multibranch |
| Secrets | Credentials + bindings |
| Server | Controller + agents |
| Hardening | Auth matrix, agent trust |
Rules & Handoff
03 / The Golden Rule
If a paragraph would be true for GitHub Actions too, it belongs in the generic docs — not here. Jenkins files contain only what is distinctively Jenkins.
04 / Reading Order
Begin in Jenkins Architecture — controller, agents, and executors first, because every later PDF assumes them.
⏩️ Next: Topology
Topology
Picking up from the Domain map — we now examine the controller–agent topology that every pipeline, agent, and credential later plugs into.
01 / The Three Parts
- Controller — holds config (JENKINS_HOME), queue, history, UI/API, credentials. Runs no builds in production.
- Agent — a machine offering executors: numbered slots, one build each.
- Remoting — the channel shipping work out. Inbound = agent dials out (survives NAT); SSH = controller dials in (flat networks).
02 / What Lives in JENKINS_HOME
| Path | Holds |
|---|---|
| jobs/ | Job configs + build history |
| workspace/ | Checked-out code (rebuildable, deletable) |
| credentials.xml + secrets/ | Encrypted secrets — back up securely |
| config.xml | Global configuration |
Failures & Handoff
05 / Failure Modes
- Disk fills with old builds → UI freezes; fix with build discarders + log rotation.
- Everything pinned to built-in node → single contention point; fix with labeled agents.
- Clock skew → signatures/webhooks fail; run NTP everywhere.
Controller schedules, serves, stores. Agents execute — nothing else.
06 / Handoff
Topology understood — now build one. Continue in Jenkins Setup.
⏩️ Next: Setup
Setup
Picking up from Architecture, where the topology was defined — we now run it: one container, one volume, one socket.
01 / Run & Unlock
$ docker volume create jenkins_home $ docker run -d --name jenkins \ -p 8080:8080 -p 50000:50000 \ -v jenkins_home:/var/jenkins_home \ -v /var/run/docker.sock:/var/run/docker.sock \ jenkins/jenkins:2.516-lts-jdk17 $ docker exec jenkins cat /var/jenkins_home/secrets/initialAdminPassword
Open localhost:8080 → paste the password → install suggested plugins → create admin user → set built-in executors to 0.
Platforms
02 / Where to Run It
| Method | When |
|---|---|
| Docker image | Default: dev, training, labs |
| OS package | Long-lived on-prem server |
| Kubernetes Helm | Production, ephemeral agents |
03 / Smoke Test
New Item → Pipeline → `hello` → inline script:
pipeline { agent any { stage('Hello') { echo 'alive' } } }
Build Now → green ball = controller + executors + workspace work
Seven Steps
04 / Run & Use, End to End
Harden & Handoff
05 / Production Checklist
- Persistent, backed-up JENKINS_HOME (test restore).
- Pinned image + plugin versions; deliberate upgrades.
- TLS reverse proxy + auth matrix from day one.
- Lost data on recreate = volume wasn't mounted. Port 50000 blocked = agents can't connect.
06 / Handoff
Server running and first job green — now write real pipelines. Continue in Jenkins Pipelines.
⏩️ Next: Jenkinsfiles
Jenkinsfiles
Picking up from Setup, where the first smoke job went green — we now write production Jenkinsfiles: Declarative structure, multibranch, and the full CI→CD arc.
01 / Generic → Jenkins
| Generic | Jenkins |
|---|---|
| Pipeline | pipeline { … } in Jenkinsfile |
| Stage / Step | stage('Build') / sh, echo, plugin steps |
| Runner | agent directive (label, docker, any) |
| Artifact | archiveArtifacts / pushed image |
02 / Declarative vs Scripted
Canonical
03 / Canonical Jenkinsfile
pipeline { agent { label 'linux' } stages { stage('Build') { steps { sh 'npm ci && npm run build' } } stage('Test') { steps { sh 'npm test' } post { always { junit 'reports/**/*.xml' } } } stage('Image') { steps { sh 'docker build -t registry/app:$GIT_COMMIT .' } } } post { failure { mail to: 'team@acme.io' } } }
04 / Multibranch = PR Gates
A Multibranch job auto-discovers branches/PRs containing a Jenkinsfile and builds each independently — the Jenkins-native PR gate. Prefer it over hand-wired jobs per branch.
DinD & Handoff
06 / Socket vs DinD
| Socket mount | DinD | |
|---|---|---|
| Isolation | Weak — shared daemon | Strong — own daemon |
| Risk | Malicious build = host root | Blast radius: dind container |
| Use when | Trusted teams (fast) | Untrusted builds |
- agent any everywhere → builds land on controller; use labeled agents.
- Inline scripts → unreviewable; keep Jenkinsfiles in the repo.
- Giant single stage → no visibility; mirror build/test/scan 1:1.
Declarative for 95% (validated, readable); Scripted for dynamic stages and advanced flow.
07 / Handoff
Pipelines need a language upgrade next: the Groovy subset that powers them lives in Groovy Essentials.
⏩️ Next: Agents
Agents
Picking up from Groovy — pipelines written, language in hand — we now provision the machines that execute them.
01 / Three Kinds
| Type | Lifecycle | Best for |
|---|---|---|
| Permanent | Long-lived VM | Special HW, Windows/GPU |
| Docker cloud | Container per build | Default Linux — clean every run |
| Kubernetes | Pod per build | Elastic, bursty CI |
02 / Labels & Executors
agent { label 'linux && docker' } // must have BOTH
agent { docker { image 'node:20' } } // ephemeral container
agent none // each stage picks
Agent Wiring
03 / Connection & Trust
- Inbound — agent dials out via WebSocket; survives NAT, needs port 50000.
- SSH — controller dials in; simple on flat networks, needs port 22 + credential.
- Ephemeral wins — pristine container per run kills "works on my machine" and tool drift.
Never run untrusted fork PRs on permanent agents holding deploy credentials. Forks get isolated, credential-free agents — a malicious workflow otherwise owns your box.
- Label typo → queue forever; check Executor Status.
- Too many executors per CPU → starvation.
04 / Handoff
Agents run the work — next they need secrets. Continue in Jenkins Credentials.
⏩️ Next: Groovy
Groovy Core
Picking up from Pipelines, where Declarative met Scripted — this is the Groovy subset both run on.
01 / Strings, Collections, Conditionals
// "double quotes" interpolate, 'single' don't def tag = env.GIT_COMMIT.take(7) echo "Building ${app}:${tag}" stages.each { s -> echo "stage: ${s}" } def failed = results.findAll { k, v -> v != 'SUCCESS' } def env2 = env.BRANCH_NAME == 'main' ? 'prod' : 'staging'
Power
02 / Dynamic Stages, Safe Nulls, Maps
// one stage per service — impossible in pure Declarative ['api','web','worker'].each { svc -> stage("Test ${svc}") { sh "./test.sh ${svc}" } } // ?. skips nulls, ?: falls back def owner = env.CHANGE_AUTHOR?.toLowerCase() ?: 'unknown' def cfg = [retries: 3, timeout: 20] timeout(time: cfg.timeout, unit: 'MINUTES') { sh 'make ci' }
Idioms
03 / Jenkinsfile Idioms
withCredentials([string(credentialsId: 'api-token', variable: 'T')]) { sh 'curl -H "Authorization: Bearer $T" ...' } retry(3) { sh './flaky-deploy.sh' } catchError(buildResult: 'UNSTABLE') { sh './optional-audit.sh' }
04 / Sandbox Gotchas
| Code | Fix |
|---|---|
| new File().text | Use readFile step |
| System.getenv() | Use env.X |
| .execute() | Use sh step |
⏩️ Next: Credentials
Credentials
Picking up from Agents, where executors run untrusted build code — secrets must therefore never live in Jenkinsfiles. Enter the credentials store.
01 / Kinds & Scopes
| Kind | Holds | Binding |
|---|---|---|
| Secret text | API token | string(…) |
| Username + password | Registry login | usernamePassword(…) |
| SSH key | Git / agent auth | sshUserPrivateKey(…) |
| Secret file | kubeconfig, keystore | file(…) |
Bindings
02 / Binding in Practice
withCredentials([usernamePassword( credentialsId: 'registry-creds', usernameVariable: 'U', passwordVariable: 'P')]) { sh 'echo "$P" | docker login registry -u "$U" --password-stdin' } # Jenkins masks $U/$P in console output automatically
03 / Failure Modes
- Secret echoed or baked into an image layer → treat as compromised, rotate immediately.
- Wrong scope (System-only in pipeline) → "credentials not found"; move to Global.
- Duplicate IDs → ambiguous resolution; keep IDs unique (github-acme-app-token).
Masking is a backstop, not a guarantee. Any secret that touched a log, layer, or chat is compromised — replace by ID, zero Jenkinsfile changes.
Bindings & Handoff
04 / Handoff
Secrets stored — but who delivers all these capabilities? Continue in Jenkins Plugins, where Git, Docker, and credentials bindings themselves come from.
⏩️ Next: Plugins
Plugins
Picking up from Credentials — whose bindings are themselves a plugin — we now survey the ecosystem that makes Jenkins Jenkins.
01 / Essential Set
| Plugin | Why |
|---|---|
| Pipeline (workflow-*) | Declarative/Scripted, stage/steps |
| Git + Branch Source | Checkout, multibranch, webhooks |
| Credentials (+Binding) | Secret storage + withCredentials |
| Docker / Kubernetes | Ephemeral build agents |
| JUnit / Warnings NG | Test reports, analysis gates |
Discipline
02 / Pin & Stage Upgrades
# plugins.txt — pinned, version-controlled
git:5.2.1
workflow-aggregator:596.v8c21c963d92d
credentials-binding:681.v346b_f30f5d80
docker-workflow:572.v950f58993843
03 / Failure Modes
- Update-all Friday → Monday outage; update deliberately with a snapshot.
- No such DSL method → owning plugin not installed.
- Core/plugin skew → cryptic startup failures; keep LTS + compatible set.
Never bulk-update plugins before a weekend. Deliberate upgrades with a rollback snapshot, or Monday owns you.
Plugins & Handoff
04 / Handoff
Plugins installed — now connect the trigger wire. Continue in Jenkins Webhooks, where pushes become builds in seconds.
⏩️ Next: Webhooks
Webhooks
Picking up from Plugins, which delivered the Branch Source plugin — we now wire it: webhooks that turn pushes into builds.
01 / Trigger Options
| Method | Latency | Verdict |
|---|---|---|
| Webhook | Seconds | Default |
| Multibranch + webhook | Seconds | Default for PRs |
| SCM polling | Minutes | Fallback / air-gapped |
| Scheduled / manual | — | Nightly, promotions |
Webhook Wiring
02 / GitHub Webhook Setup
1. Job: enable GitHub hook trigger for GITScm polling 2. Repo → Settings → Webhooks → Add: Payload URL https://jenkins.acme.io/github-webhook/ events: push + pull requests 3. Push → GitHub Hook Log shows delivery → build in seconds # private nets: controller needs a reachable URL (reverse proxy / ngrok)
03 / Multibranch = PR Gates
Multibranch scans the repo, builds each branch/PR Jenkinsfile independently, reports status to GitHub checks. Branch deleted → job auto-removed. No hand-wired jobs per branch, ever.
- 403/404 → wrong URL (trailing slash matters) or missing plugin.
- Not triggering → trigger checkbox off; check Hook Log.
- Duplicates → webhook + polling both on; disable polling.
- Validate webhook secrets — or anyone curls your builds.
Webhooks & Handoff
04 / Handoff
Triggers fire — but open triggers are an attack surface. Continue in Jenkins Security, where authentication, authorization, and agent trust lock this down.
⏩️ Next: Security
Security
Picking up from Webhooks, where anyone-with-curl could fire builds — we now decide who may do what.
01 / Authentication & Authorization
| Role | Grants |
|---|---|
| Developers | Job/Build + Read |
| Leads | + Configure / Cancel |
| Admins | Overall / Administer |
Trust
02 / Agent-to-Controller Distrust
- Builds execute attacker-influenced code — default deny on Agent → Controller access.
- Ephemeral agents: a compromised container dies with the build.
- Fork PRs → isolated, credential-free agents. Never shared permanent ones.
03 / Secrets & Updates
- Secrets only via bindings; set +x around manual handling; TLS-only admin.
- Rotate by ID replacement; deprovision SSO, don't rely on memory.
- CVEs cluster in plugins: staging validates → snapshot → production.
JENKINS_HOME/secrets decrypts the whole store. Its exposure = everything is compromised. Rotate all of it.
PR contents are attacker-influenced code running on your agents — isolate execution and scope credentials.
Security & Handoff
04 / Handoff
Hardened core — now scale the craft. Continue in Jenkins Advanced: shared libraries, matrix builds, JCasC, and backup/restore.
⏩️ Next: Advanced
Advanced
Picking up from Security, where trust boundaries were drawn — shared libraries run outside the sandbox, so that trust model governs them.
01 / Shared Libraries
// Jenkinsfile: one line replaces 60 of boilerplate @Library('acme-pipeline-lib@1.4') _ standardServicePipeline(app: 'shop', deployEnv: 'staging')
02 / Parallel & Matrix
Parallelize independent verification (unit/lint/scan), never dependent deploys. Matrix multiplies stages × axes (JDK 17/21, browsers). Size agent pools for peak fan-out, not average load.
As Code
03 / Controller From YAML
# jenkins.yaml — identical controller every boot jenkins: { numExecutors: 0 } credentials: { system: { … registry-token: "${REGISTRY_TOKEN}" } } # boot: pinned image + plugins.txt + jenkins.yaml. UI drift is ephemeral.
04 / Backup, Console, Tuning
- Backup JENKINS_HOME minus workspaces; restore jobs + credentials + config + YAML + plugins. Untested backup = rumor. Encrypt off-site.
- Script Console = Groovy as admin; audit every run; never paste blind snippets.
- Queue — executors ≤ ~1 per 1–2 cores; heap ≥ 4 GB (-Xmx4g); stagger cron (H 9 *); quiet periods batch rapid commits.
Check & Handoff
05 / Interview Check
Version + unit-test the lib, migrate one pilot repo, pin tags, admin-approve the repo (unsandboxed trust).
Image → plugins → JCasC → secrets → backup restore → smoke pipeline. Secrets break first.
06 / Handoff
Advanced patterns banked — when they break, diagnose in order. Continue in Jenkins Troubleshooting.
⏩️ Next: Troubleshooting
Triage
Picking up from Advanced, where moving parts multiplied — this is the diagnostic order that untangles them.
01 / Triage Table
| Symptom | Check | Fix |
|---|---|---|
| Stuck in queue | Executor Status, labels, agents | Fix typo, free executor |
| No such DSL method | Owning plugin installed? | Install / pin plugin |
| command not found | Tool on that agent? | Matching label / Docker image |
| Clone/auth failure | Credential ID + scope | Rebind Global credential |
| Webhook silent | Hook Log, checkbox | Fix URL, enable trigger |
| Controller frozen | Disk, heap (-Xmx4g) | Discard builds, raise heap |
Logs & Recovery
02 / Reading a Build Log
- First red line = effect; scroll up for the cause (exit code, Groovy stack).
- Replay button re-runs edited pipelines without pushing commits.
- Wipe workspace + rebuild separates dirty-workspace flakes from real failures.
03 / Sandbox & Recovery
RECOVERY — bad config? Restore config.xml + Reload Configuration (no restart). Disaster? Restore JENKINS_HOME backup to a fresh pinned image, replay the smoke pipeline.
04 / Handoff
Jenkins domain complete — now meet the sibling implementation. Continue in GitHub Actions: hosted runners, YAML, zero infrastructure.
📇 Quick Revision — Terms Table
| Controller | Schedules, serves UI/API, stores config, history and credentials. Runs zero builds in production. |
| Agent | A machine offering executors that run builds. Permanent, Docker cloud, or Kubernetes. |
| Executor | One numbered build slot on an agent, roughly one per 1–2 cores. |
| Remoting | Channel shipping work to agents. Inbound = agent dials out; SSH = controller dials in. |
| JENKINS_HOME | Controller data: jobs/, workspace/, credentials.xml + secrets/, config.xml. Back up securely. |
| Jenkinsfile | Pipeline as code in the repo. Declarative pipeline { … } or Scripted node { … }. |
| Declarative | Opinionated validated pipeline syntax. Default for 95% of Jenkinsfiles. |
| Scripted | Raw Groovy pipelines for dynamic stages and advanced flow. |
| Multibranch | Job discovering every branch/PR Jenkinsfile and building each independently. |
| Label | Capability tag matching jobs to agents, e.g. linux && docker. Typos queue forever. |
| Credentials store | Encrypted vault keyed by stable IDs. Values never appear in code or logs. |
| withCredentials | Binding step exposing secrets as masked variables inside sh blocks. |
| Shared library | Versioned Groovy lib (@1.4, never @main) replacing boilerplate. Unsandboxed, admin-approved. |
| JCasC | Controller from YAML: identical controller every boot from jenkins.yaml. |
| Plugin | Capability unit. Pin in plugins.txt, upgrade in staging first, remove unused ones. |
| Webhook | /github-webhook/ trigger turning pushes into builds in seconds. |
| Sandbox | Allowlist restricting untrusted Groovy. Prefer allowlisted steps over approvals. |
| LTS | Long-term-support line cut every ~4 weeks. Production default over weeklies. |
🎤 Concept Questions — Distilled Answers
Controller schedules, serves and stores. Agents execute — nothing else.
Declarative for 95%: validated, readable. Scripted for dynamic stages and advanced flow.
Label is a capability tag matching jobs to agents. Executor is one build slot.
So no build ever lands on the controller — it is a single contention point, not a worker.
Treat as compromised and rotate by ID immediately. Masking is a backstop, not a guarantee.
Multibranch auto-discovers branches/PRs, gates each, reports checks, removes dead branches. Never hand-wire.
Socket is fast for trusted teams but shares the daemon. DinD isolates untrusted builds.
Pinned image → plugins → JCasC → secrets → backup restore → smoke pipeline. Secrets break first.
📌 Command Cheat Sheet
docker volume create jenkins_home | persistent controller data |
docker run -d -p 8080:8080 -p 50000:50000 -v jenkins_home:/var/jenkins_home jenkins/jenkins:2.516-lts-jdk17 | pinned LTS controller |
docker exec jenkins cat /var/jenkins_home/secrets/initialAdminPassword | first unlock password |
pipeline { agent { label 'linux' } } | labeled agent, never any |
stage('Test') { steps { sh 'npm test' } } | mirrored build/test/scan stages |
post { always { junit 'reports/**/*.xml' } } | test report gate |
withCredentials([string(credentialsId: 'api-token', variable: 'T')]) | masked secret binding |
retry(3) { sh './flaky-deploy.sh' } | transient-failure retry |
@Library('acme-pipeline-lib@1.4') _ | versioned shared library |
🧪 Self-Quiz + Answer Key
- jobs/, workspace/, credentials.xml + secrets/, config.xml.
- Inbound: agent dials out, survives NAT. SSH: controller dials in on flat networks.
- Run, unlock, lock controller, agent, multibranch job, webhook, verify loop.
- Per-branch/PR builds, GitHub checks, auto-removal of dead branches.
- new File → readFile; System.getenv → env.X; .execute() → sh.
- Never bulk-update plugins before a weekend. Stage first, keep a snapshot.
- Developers build, leads configure/cancel, admins administer. Deny by default.
- Effect — scroll up for the cause, then replay or wipe the workspace.