Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 40 ยท Pipeline as Code

Declarative Pipeline Syntax in Depth

Learn every part of a declarative Jenkinsfile: agent, options, triggers, environment, tools, parameters, stages, post and when, plus the linter and common syntax errors.

A declarative Jenkins Pipeline is a strict, readable outline. Instead of writing a free-form program, you fill in named sections (such as agent, stages and post) and directives (such as options, environment and when) in a fixed shape. Jenkins checks that shape before the build starts, so many mistakes show up in seconds instead of halfway through a run.

Pipeline Basics and the Jenkinsfile showed a first working pipeline. This lesson walks through every block you can put in one, what each is for, and what Jenkins says when you get it wrong. The real syntax is shown in read-only blocks, because a web page cannot run Jenkins. The runnable examples are stand-ins: small JavaScript programs that model the rules of the shape, so you can see how a validator thinks.

The skeleton of a Jenkinsfile

agent Where the work runs.
stages The ordered list of stage blocks.
steps The actual commands inside a stage.
post What to do when it ends.

agent, stages and at least one stage with steps are required.

1 / 2

The smallest valid pipeline

Everything lives inside one pipeline { } block. A pipeline needs an agent, a stages section, and each stage needs a name and a steps block.

GROOVY
pipeline {
  agent any
  stages {
    stage('Hello') {
      steps {
        echo 'Hello from a declarative pipeline'
      }
    }
  }
}

Two details trip up beginners. First, strings in steps are Groovy strings, so single quotes mean "plain text" and double quotes mean "interpolate ${...}". Second, a stage name is a string you choose, and it becomes the label in the stage view, so keep it short and meaningful.

A pipeline with most of the pieces

Here is a realistic skeleton. Read it top to bottom; each block is explained below.

GROOVY
pipeline {
  agent { label 'linux' }

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

  triggers {
    cron('H 2 * * 1-5')
  }

  parameters {
    string(name: 'TARGET', defaultValue: 'staging', description: 'Where to deploy')
    booleanParam(name: 'RUN_SLOW_TESTS', defaultValue: false)
  }

  environment {
    APP_NAME = 'shop'
  }

  stages {
    stage('Build') {
      steps { sh './build.sh' }
    }
    stage('Test') {
      steps { sh './test.sh' }
    }
    stage('Deploy') {
      when { branch 'main' }
      steps { sh "./deploy.sh ${params.TARGET}" }
    }
  }

  post {
    always  { echo 'Finished' }
    failure { echo 'Something broke' }
  }
}

agent

agent says which machine (or container) runs the stages. The common forms are:

  • agent any: run on any available agent.
  • agent none: do not allocate an agent for the whole pipeline; every stage must then declare its own agent. This is useful when a stage only waits for a human, because you do not want to hold an executor while someone is at lunch.
  • agent { label 'linux' }: run on an agent with that label.
  • agent { docker { image 'node:22' } }: run inside a container (see Docker Agents and Building Images).

An agent can appear at the top level and again inside any stage, and the stage version wins for that stage.

options

options holds settings for the whole pipeline (or, for a few of them, for one stage). The ones you will use most:

  • timeout(time: 30, unit: 'MINUTES') aborts a build that runs too long. Without it, a hung step can occupy an executor forever.
  • buildDiscarder(logRotator(numToKeepStr: '20')) keeps only the last 20 builds so the disk does not fill up.
  • disableConcurrentBuilds() stops two builds of the same job from running at once. Useful when builds share a deploy target.
  • retry(3) re-runs the whole pipeline on failure; most people prefer retry on a single flaky step instead.
  • skipDefaultCheckout() turns off the automatic source checkout, for the rare job that wants to control it.
  • timestamps() adds a time to every console line. It comes from a plugin, so it exists only where that plugin is installed.

triggers

triggers starts builds without a person clicking. cron('H 2 * * 1-5') runs on a schedule, and pollSCM('H/5 * * * *') asks the repository for changes every few minutes. The H means "hash": Jenkins picks a stable minute based on the job name so that a hundred jobs do not all start at exactly 02:00. Webhooks are more efficient than polling, and the whole topic gets its own lesson: Triggers: Webhooks, Polling and Schedules.

environment

environment defines variables that every step can read. In a sh step they are ordinary shell variables ($APP_NAME), and in Groovy code you read them as env.APP_NAME. The same block can also hold secrets with credentials('id'), which is covered in Credentials and Secrets. A stage can have its own environment block too. More on resolution rules in Environment Variables and Parameters.

tools

tools makes a configured tool available on the PATH for the pipeline or a single stage:

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

The names (maven-3.9, temurin-21) are not magic: an administrator defined them under Manage Jenkins, Tools. If you use a name nobody configured, the build fails with a message saying the tool is not defined.

parameters

parameters declares the inputs shown on the "Build with Parameters" page. Types include string, text, booleanParam, choice and password. Inside the pipeline you read them as params.TARGET. A subtle point: Jenkins learns about the parameters when a build of the pipeline runs, so a newly added parameter appears on the page after the first run that contains it.

stages, steps and the stage rules

stages contains one or more stage blocks. Each stage contains exactly one of these: steps, stages (sequential nested stages), parallel, or matrix. You cannot mix them in one stage. Inside a stage you can also put its own agent, environment, options, tools, input, when and post. The chapter on Stages, Parallel and Matrix covers the running order in detail.

steps holds the commands. Anything that is real Groovy code (loops, variables, if) must be wrapped in a script { } step, because declarative steps only accepts steps. Common Steps explains that boundary.

post

post runs after the stages and picks blocks by outcome: always, success, failure, unstable, aborted, changed, fixed, regression, unsuccessful and cleanup. A stage can have its own post too. See Conditions and Post Actions.

when

when is a stage-level directive that decides whether the stage runs, for example when { branch 'main' }. It never appears at the top level of the pipeline.

Syntax errors and the linter

Declarative pipelines are validated before any step runs. Jenkins parses the whole file and, if the shape is wrong, fails the build immediately with an error such as:

TEXT
WorkflowScript: 12: Expected a step @ line 12, column 9.
WorkflowScript: 3: Missing required section "stages" @ line 3, column 1.
WorkflowScript: 9: Undefined section "foo" @ line 9, column 5.

The line number points at the problem (sometimes the line after it, when a brace is missing). To catch these without starting a build, use the Pipeline linter: Jenkins exposes a validate endpoint that you can call with curl and the Jenkinsfile, there is a command in the Jenkins CLI, and IDE plugins for editors use the same service. The exact call, and the way you authenticate, depends on your server, so check the page for your Jenkins version.

A linter cannot run your commands, but it can check structure. The stand-in below models that idea: it represents a pipeline as a JavaScript object and applies a few of the real rules.

Node.js A stand-in structure validator

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The good pipeline passes. The bad one shows four mistakes: a when block at the top level (it belongs inside a stage), a stage that has both steps and parallel, a nameless stage, and a made-up post condition. The real linter reports similar problems with line numbers. Remember that this is a model; real Jenkins knows many more rules, such as which options are allowed where.

To feel the reverse direction, here is a tiny program that prints a pipeline from a description. Writing the structure as data is how generators, shared libraries and templates work.

JS Generating a Jenkinsfile from data

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

No output.

Common beginner mistakes

  • Writing Groovy code (a for loop, def x = 1) directly in steps. Wrap it in script { }.
  • Using double quotes around a string with a $ that you wanted the shell to expand. Groovy expands it first. Use single quotes, or escape the dollar sign.
  • Forgetting that agent none needs an agent in every stage.
  • Putting when or input at the top level.
  • Naming a tool that was never configured in Manage Jenkins, Tools.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which sections are required in every declarative pipeline?

    A declarative pipeline needs an agent and a stages section, and each stage needs a name and a body such as steps. The rest are optional.
  2. 2. Where does a when directive belong?

    when decides whether one stage runs, so it is written inside that stage.
  3. 3. What does the H in cron('H 2 * * *') mean?

    H lets Jenkins choose a repeatable value derived from the job name so many jobs do not all start at the same moment.
  4. 4. You need a for loop inside a declarative stage. What do you do?

    Declarative steps accepts only steps. The script step opens a block of ordinary Groovy where loops and variables are allowed.

Summary

  • A declarative pipeline is one pipeline { } block with named sections; agent and stages are required.
  • options, triggers, environment, tools and parameters configure the run; post handles outcomes; when belongs inside a stage.
  • A stage has exactly one of steps, stages, parallel or matrix.
  • Jenkins validates the structure before running; the linter lets you check without building.
  • Real Groovy code goes inside script { }.

Next, learn the steps that do the actual work in Common Steps: sh, bat, echo, dir, withEnv.