Anatomy of a declarative Jenkinsfile
One pipeline block, a mandatory agent, stages of steps, and a post block that runs whatever happened.
Open this lesson in the learning hubKey points
- A declarative pipeline is a single
pipelineblock; anything outside it is plain Groovy and is not validated. agentis mandatory at the top, andagent noneforces every stage to declare where it runs.- Every
stageneeds exactly one ofsteps,stages,parallelormatrix. - The
postblock runs after the stages, withalwaysevaluated first andcleanuplast. - Declarative checks the repo out on every agent for you unless
optionssetsskipDefaultCheckout. - Use
scriptonly 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.