Opscraft
Jenkinsfile · Lesson 2 of 10 · 6 min read

The declarative skeleton, directive by directive

pipeline {
  agent none                                    // where to run (top-level or per stage)
  options { ... }                               // job-wide behaviour
  parameters { ... }                            // build parameters
  environment { ... }                           // environment variables (and credentials)
  triggers { ... }                              // cron / pollSCM / upstream
  tools { ... }                                 // auto-installed tools (maven, jdk, nodejs)
  libraries { lib('platform-lib@v2') }          // alternative to @Library
  stages {
    stage('Name') {
      agent { ... }                             // per-stage agent
      environment { ... }                       // per-stage env
      options { ... }                           // per-stage options (timeout, retry, skipDefaultCheckout)
      when { ... }                              // condition
      input { ... }                             // pause for approval before the stage
      steps { ... }                             // the actual work
      post { ... }                              // per-stage post actions
    }
  }
  post { ... }                                  // pipeline-level post actions
}
Enlarge diagramPIPELINE { }STAGES { } → STAGE('BUILD') { }agentoptionsparametersenvironmenttriggersagentwheninputstepspostpost { always · failure · fixed · cleanup }steps holds the real work; everything else in a stage is optional
Figure 1. The shape of a declarative pipeline: settings for the whole run at the top, stages in the middle, post actions at the end.
Swipe sideways to see all of it, or tap to open it full screen.

options

Option Purpose
timeout(time: 45, unit: 'MINUTES') Abort the whole run (or a stage) if it hangs
buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '5')) Retention — protects controller disk
disableConcurrentBuilds() One run of this job/branch at a time (abortPrevious: true cancels the older one — great for PR builds)
timestamps() Timestamp every console line
skipDefaultCheckout() Don't auto-checkout; you call checkout scm yourself
retry(2) Retry the whole pipeline/stage on failure
parallelsAlwaysFailFast() Make all parallel blocks fail fast
quietPeriod(30) Wait before starting (batch rapid commits)
preserveStashes(buildCount: 5) Keep stashes so "Restart from Stage" works
durabilityHint('PERFORMANCE_OPTIMIZED') Fewer checkpoints, faster, less resilient to controller restarts
ansiColor('xterm') Coloured output (plugin)

parameters

parameters {
  choice(name: 'ENV', choices: ['staging', 'prod'], description: 'Target environment')
  string(name: 'IMAGE_TAG', defaultValue: '', description: 'Leave empty to build')
  booleanParam(name: 'RUN_E2E', defaultValue: true)
  text(name: 'NOTES', defaultValue: '')
  password(name: 'TEMP_TOKEN', defaultValue: '')     // prefer credentials instead
}

Read with params.ENV. Note: parameters defined in a Jenkinsfile only appear in the UI after the first run of that branch (the job learns them from the file).

environment

environment {
  AWS_REGION = 'ap-south-1'
  REGISTRY   = '123456789012.dkr.ecr.ap-south-1.amazonaws.com'
  IMAGE      = "${REGISTRY}/orders"
  SONAR      = credentials('sonar-token')          // secret text → $SONAR (masked)
  NEXUS      = credentials('nexus-creds')          // user/pass → $NEXUS, $NEXUS_USR, $NEXUS_PSW
  KUBECONFIG = credentials('staging-kubeconfig')   // secret file → path to a temp file
}

Environment values are strings. Variables set in environment are available as env.NAME in Groovy and $NAME in shell.

Enlarge diagramsecret textusername + passwordsecret fileSONAR = credentials('sonar-token')→ $SONARNEXUS = credentials('nexus-creds')→ $NEXUS, $NEXUS_USR, $NEXUS_PSWKUBECONFIG = credentials('kubeconfig')→ path to a temp file
Figure 2. credentials() in environment binds a secret to variables for the whole run, masked in the log. The variables depend on the credential type.
Swipe sideways to see all of it, or tap to open it full screen.

triggers

triggers {
  cron('H 2 * * 1-5')                      // nightly on weekdays, hashed minute
  pollSCM('H/15 * * * *')                  // fallback when webhooks can't reach Jenkins
  upstream(upstreamProjects: 'platform/base-image/main', threshold: hudson.model.Result.SUCCESS)
}

For multibranch jobs, branch/PR builds are triggered by webhooks through the branch source; triggers adds schedules.

tools

tools { jdk 'temurin-21'; maven 'maven-3.9' }

Names refer to tool installations configured globally. With container-based agents, you usually pick a tool image instead and skip tools.

post conditions

Evaluated in this order after the stages (or after a stage, for stage-level post):

Condition Runs when
always Always
changed Result differs from the previous run
fixed Previous run failed/unstable, this one succeeded
regression Previous succeeded, this one failed/unstable/aborted
aborted Run was aborted (manually or by timeout)
failure Run failed
success Run succeeded
unstable Run is unstable (e.g. test failures recorded by junit)
unsuccessful Anything but success
cleanup Last, after all other conditions — for workspace cleanup and teardown
post {
  always   { junit allowEmptyResults: true, testResults: '**/target/surefire-reports/*.xml' }
  failure  { slackSend channel: '#orders-ci', color: 'danger', message: "FAILED ${env.JOB_NAME} #${env.BUILD_NUMBER} ${env.BUILD_URL}" }
  fixed    { slackSend channel: '#orders-ci', color: 'good', message: "Back to green: ${env.JOB_NAME}" }
  cleanup  { cleanWs() }
}
Enlarge diagramalwaysrunschangedrunsregressionrunsfailurerunsunsuccessfulrunssuccessskippedfixedskippedcleanuprunsprevious run: SUCCESS · this run: FAILURE
Figure 3. Which post blocks run for a failed build that was green last time. cleanup always runs last.
Swipe sideways to see all of it, or tap to open it full screen.