Opscraft
Jenkinsfile · Lesson 1 of 10 · 3 min read

Declarative vs scripted pipelines

A Jenkinsfile defines a pipeline as code, stored and reviewed alongside the application. Interviews typically ask you to write or critique one on a whiteboard: build → test → scan → push → deploy to staging → approval → production, with parallel tests, credentials handled safely, and clean failure handling. This topic is a complete reference to declarative syntax plus the patterns that make pipelines fast, safe and maintainable.

Two syntaxes, one engine

Both run on the same Pipeline engine (CPS Groovy). They differ in structure:

// Declarative
pipeline {
  agent { label 'linux' }
  stages {
    stage('Build') { steps { sh 'make build' } }
  }
  post { always { cleanWs() } }
}
// Scripted
node('linux') {
  try {
    stage('Build') { sh 'make build' }
  } finally {
    cleanWs()
  }
}
Declarative Scripted
Structure Fixed, opinionated blocks (pipeline, agent, stages, post...) Free-form Groovy
Validation Syntax checked before the run starts; clear errors Errors appear at runtime, mid-build
Readability Consistent across teams; UI tooling (Restart from Stage, Blue Ocean, directive generator) Depends on the author
Flexibility Arbitrary logic only inside script {} or library steps Unlimited
Built-ins post, when, options, matrix, parallel, input directive You write try/catch/finally yourself

Senior recommendation: declarative by default; keep script {} blocks small; move complex logic into shared-library steps. Scripted pipelines still appear inside shared libraries and in older estates — you should be able to read them.

Enlarge diagramDeclarative: pipeline { }Scripted: node { }Fixed structure, validated before runningBuilt-in post, when, options, inputRestart from stageEasy to read and reviewAny Groovy: loops, functionsNo structure enforcedHarder to read and lintMostly inside shared libraries now
Figure 1. Declarative and scripted pipelines run on the same engine. Declarative is the default for new pipelines; scripted is plain Groovy.
Swipe sideways to see all of it, or tap to open it full screen.

Where a Jenkinsfile comes from

  • Pipeline script from SCM / Multibranch — Jenkins checks out the repo and reads Jenkinsfile (path configurable). In declarative pipelines, checkout scm happens automatically at the start of each stage's agent unless you set options { skipDefaultCheckout() }.
  • Inline script in the job config — fine for experiments, not for real pipelines (not versioned).