Anatomy of a declarative Jenkinsfile

Jenkins CI/CD Course · lesson 4 of 15 · 6 min read

One pipeline block, a mandatory agent, stages of steps, and a post block that runs whatever happened.

Open this lesson in the learning hub

Key points

  • A declarative pipeline is a single pipeline block; anything outside it is plain Groovy and is not validated.
  • agent is mandatory at the top, and agent none forces every stage to declare where it runs.
  • Every stage needs exactly one of steps, stages, parallel or matrix.
  • The post block runs after the stages, with always evaluated first and cleanup last.
  • Declarative checks the repo out on every agent for you unless options sets skipDefaultCheckout.
  • Use script only for the bits declarative cannot express; a Jenkinsfile that is one big script block gains nothing.

Example

pipeline {
  agent { label 'linux' }

  options {
    timeout(time: 30, unit: 'MINUTES')
    buildDiscarder(logRotator(numToKeepStr: '20'))
    disableConcurrentBuilds()
    timestamps()
  }

  environment {
    APP = 'orders-api'
  }

  stages {
    stage('Build') {
      steps { sh 'mvn -B -ntp -DskipTests package' }
    }
    stage('Test') {
      steps { sh 'mvn -B -ntp -Dmaven.test.failure.ignore=true test' }
      post {
        always { junit '**/target/surefire-reports/*.xml' }
      }
    }
  }

  post {
    always   { echo "Result: ${currentBuild.currentResult}" }
    success  { archiveArtifacts artifacts: 'target/*.jar', fingerprint: true }
    unstable { echo 'Tests failed - build is UNSTABLE, not FAILURE.' }
    failure  { echo 'A step exited non-zero.' }
    cleanup  { cleanWs() }
  }
}

Declarative gives you structure, validation and a post block; scripted gives you Groovy, and you rarely need all of it.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Jenkins CI/CD Course course, and every lesson in it is listed on the Jenkins CI/CD Course contents page.