Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 40 ยท Practice and Review

Jenkins Cheat Sheet

A compact Jenkins cheat sheet: Jenkinsfile skeleton, directives, common steps, environment variables, cron syntax, URL and CLI tricks and a troubleshooting table.

This is the page to keep open in a tab while you work. It does not replace the lessons; each section links to the lesson that explains the idea. Think of it as a map. The code on this page is real Jenkins syntax, so it is read-only (a Jenkins server cannot run inside a web page), and two small JavaScript stand-ins at the end explain cron expressions and build the common URLs for you. The stand-ins are helper tools for learning, not part of Jenkins.

What is on this page

Jenkinsfile Skeleton, directives and steps.
Cron Five fields and the H symbol.
URLs and CLI Trigger, inspect and restart.
Troubleshooting Symptom to fix at a glance.

Keep it open while you work.

1 / 2

Jenkinsfile skeleton

GROOVY
@Library('[email protected]') _          // optional, pin the version

pipeline {
  agent { label 'linux' }            // or: agent none, docker { image '...' }
  options {
    timeout(time: 30, unit: 'MINUTES')
    buildDiscarder(logRotator(numToKeepStr: '30'))
    disableConcurrentBuilds()
  }
  parameters {
    string(name: 'VERSION', defaultValue: '1.0.0')
    booleanParam(name: 'DRY_RUN', defaultValue: true)
  }
  triggers { cron('H 2 * * 1-5') }
  environment {
    APP = 'shop'
    TOKEN = credentials('deploy-token')   // secret text, masked in logs
  }
  stages {
    stage('Build') {
      steps { sh 'make build' }
    }
    stage('Test') {
      steps { sh 'make test' }
      post { always { junit 'reports/*.xml' } }
    }
    stage('Deploy') {
      when { branch 'main' }
      steps { sh './deploy.sh' }
    }
  }
  post {
    failure { echo 'Build failed' }
    cleanup { cleanWs() }
  }
}

See Pipeline Basics and the Jenkinsfile and Declarative Pipeline Syntax in Depth.

Directives and sections

Section Purpose
agent Where to run: any, none, { label '...' }, { docker { image '...' } }
options Timeout, retention, concurrency, retry, timestamps
parameters Inputs: string, choice, booleanParam, text, password
triggers cron(...), pollSCM(...), upstream(...)
environment Variables; credentials('id') binds secrets
tools Tools configured in Jenkins (JDK, Maven)
stages / stage Ordered phases
steps The actions inside a stage
when Skip a stage: branch, expression, changeset, anyOf, allOf, not
parallel / matrix Concurrent branches or axis combinations
post After-run actions by result
input Pause for approval inside a stage

Useful when helpers: beforeAgent true (decide before allocating an agent) and beforeInput true.

Common steps

Step Example
Shell sh 'make', sh(script: 'git rev-parse HEAD', returnStdout: true).trim()
Windows batch bat 'build.cmd'
Print echo "Building ${env.BUILD_NUMBER}"
Directory dir('services/api') { sh 'make' }
Retry / timeout retry(3) { ... }, timeout(time: 5, unit: 'MINUTES') { ... }
Sleep sleep 10 (seconds)
Script block script { def x = 1 }
Mark result unstable('tests flaky'), error('stop here')
Catch and continue catchError(buildResult: 'UNSTABLE', stageResult: 'FAILURE') { ... }
Credentials withCredentials([string(credentialsId: 'id', variable: 'T')]) { sh 'use "$T"' }
Env for a block withEnv(['A=1']) { sh 'echo $A' }
Test report junit 'build/test-results/**/*.xml'
Artifacts archiveArtifacts artifacts: 'dist/**', fingerprint: true
Stash stash name: 'dist', includes: 'dist/**' then unstash 'dist'
Clean workspace cleanWs()
Git checkout scm, git url: '...', branch: 'main'
Approval input message: 'Deploy?', ok: 'Yes'
Mail mail to: '[email protected]', subject: '...', body: '...'

See Common Steps and Credentials and Secrets. Remember: use single quotes for sh when the shell should expand a secret.

Environment variables

Variable Meaning
BUILD_NUMBER The number of this build
BUILD_ID The build identifier (usually the number)
BUILD_URL Full URL of this build
JOB_NAME Full job name, including folders
JOB_BASE_NAME Job name without folders
WORKSPACE Absolute path of the workspace
NODE_NAME Name of the agent running the build
EXECUTOR_NUMBER Executor index on the agent
JENKINS_URL Base URL of the controller
GIT_COMMIT, GIT_BRANCH, GIT_URL Set after a Git checkout
BRANCH_NAME Branch in multibranch jobs
CHANGE_ID, CHANGE_TARGET Pull request number and target branch
TAG_NAME Set when building a tag

In pipelines you can read them as env.BUILD_NUMBER or ${BUILD_NUMBER}; parameters are params.NAME and also appear as environment variables. See Environment Variables and Parameters.

Cron syntax

TEXT
MINUTE  HOUR  DAY-OF-MONTH  MONTH  DAY-OF-WEEK
0-59    0-23  1-31          1-12   0-7  (0 and 7 are Sunday)
Expression Meaning
H 2 * * 1-5 Once in the 2 a.m. hour, weekdays, at a job-specific minute
H/15 * * * * Every 15 minutes with a per-job offset
H(0-29)/10 * * * * Every 10 minutes, offset chosen from the first half hour
H H(8-17) * * 1-5 Once during working hours on weekdays
*/5 * * * * Every 5 minutes at exact multiples (all jobs fire together)
@daily, @hourly, @weekly, @monthly Aliases that also use H

H spreads load: use it instead of 0 and */5 unless an exact time matters. See Triggers: Webhooks, Polling and Schedules.

URLs and command line

Goal URL or command
Pipeline syntax helper /pipeline-syntax/
Console text of last build /job/NAME/lastBuild/consoleText
Trigger a build (POST) /job/NAME/build?token=TOKEN
Trigger with parameters (POST) /job/NAME/buildWithParameters?KEY=value
JSON data /job/NAME/api/json?tree=builds[number,result]
Validate a Jenkinsfile POST /pipeline-model-converter/validate with form field jenkinsfile
Script console (admin only) /script
Plugin manager /pluginManager/
Stop accepting builds /quietDown, undo with /cancelQuietDown
Restart when idle /safeRestart
Reload config from disk /reload

Jobs inside folders repeat /job/: folder team and job app is /job/team/job/app/.

Terminal
# API token authentication (create the token in your user settings)
curl -u alice:API_TOKEN -X POST "https://jenkins.example.com/job/app/buildWithParameters?ENVIRONMENT=staging"

# Validate a Jenkinsfile without running it
curl -u alice:API_TOKEN -X POST -F "jenkinsfile=<Jenkinsfile" \
  https://jenkins.example.com/pipeline-model-converter/validate

# Command line client
java -jar jenkins-cli.jar -s https://jenkins.example.com/ -auth alice:API_TOKEN who-am-i
java -jar jenkins-cli.jar -s https://jenkins.example.com/ -auth alice:API_TOKEN build app -p VERSION=1.2.3 -s -v

# Install plugins from a pinned list (image build time)
jenkins-plugin-cli -f plugins.txt

Depending on your security settings, POST requests may need a CSRF crumb when you use a password; API tokens avoid that.

Troubleshooting table

Symptom Likely cause First move
"Waiting for next available executor" All executors busy or label has no online agent Read the queue reason; check label spelling and agent status
Build never ends No timeout, hung process Add timeout; use Stop, then Terminate or Kill on the build page
NotSerializableException Non-serializable object kept across steps Keep it in a @NonCPS method or avoid storing it
Scripts not permitted to use method ... Sandbox blocks the call Review it, then approve in script approval or use a safe step
command not found in sh Tool missing on that agent Fix the agent image or use tools/a container
Disk full on controller No retention, builds on controller buildDiscarder, clean workspaces, move builds to agents
Old files affect new build Reused workspace cleanWs() or fresh containers
Webhook does nothing Wrong URL, token or network path Check the Git host's delivery log and Jenkins' log
Plugin broke after update Incompatible version Roll back to the pinned version, test updates in staging

More depth in Backup, Monitoring and Troubleshooting.

Stand-in 1: explain a cron expression

Paste any five-field expression into the code and it prints each field in words. It is a learning helper that understands numbers, lists, ranges, steps and H; it does not compute the real hashed minute.

JS Cron expression explainer

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The */5 and H/5 rows show why H exists: both mean "every 5 minutes", but */5 makes every job start on the same minute.

Stand-in 2: build Jenkins URLs

Folders make Jenkins URLs repetitive (/job/team/job/app/). This helper builds the common URLs from a base address and a slash-separated job name, and shows which ones need a POST. It builds strings only; nothing is sent anywhere.

JS Jenkins URL builder

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Note the encoded space (my%20app) in the last lines: names with spaces or unusual characters must be percent-encoded in URLs.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which cron expression runs once during the 3 a.m. hour on weekdays, spreading the load across jobs?

    H chooses a job-specific minute, 3 is the hour and 1-5 is Monday to Friday.
  2. 2. What is the URL path for a job named app inside a folder named team?

    Every level in the path repeats /job/.
  3. 3. Which option decides whether to run a stage before an agent is allocated?

    beforeAgent true evaluates the when condition first, so skipped stages do not wait for an executor.
  4. 4. Why use single quotes with sh when a credential is bound to $TOKEN?

    Double-quoted Groovy strings are interpolated by Jenkins before the shell runs.

Summary

  • A Jenkinsfile is pipeline { agent, options, parameters, triggers, environment, stages, post }.
  • Know the common steps and use single-quoted sh for secrets.
  • Learn the built-in environment variables; params.NAME reads parameters.
  • Cron has five fields; prefer H to spread load.
  • Folders repeat /job/ in URLs; use API tokens for scripted calls and the validator endpoint for Jenkinsfiles.
  • For problems, read the queue reason, the console and the controller log, and change one thing at a time.

You have reached the end of the Jenkins course. To go further, return to Pipeline Basics and the Jenkinsfile and rebuild your own project from scratch, or read about alternatives in What Is Jenkins?.