Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 44 ยท Jenkins

The Declarative Jenkinsfile

Write a declarative Jenkinsfile: pipeline, agent, stages, steps, environment, options, post conditions, when and parameters, with a runnable model of the flow.

A Jenkins pipeline is a program that lives in your repository, in a file named Jenkinsfile. Jenkins reads it, finds an agent to run it on, and executes the stages you described. Because the file is versioned with your code, a change to the build process goes through the same review as a change to the application.

Jenkins supports two syntaxes. Declarative pipelines have a fixed, structured shape and are what most teams should start with. Scripted pipelines are free-form Groovy and are covered in Scripted Pipelines and Shared Libraries. If you have not met the moving parts yet, read Jenkins: Controller, Agents and Jobs first.

The real Jenkins cannot run on this site: it needs a server, a controller process and agents. The Groovy below is read-only. The runnable examples are stand-ins: small programs that execute a model of a declarative pipeline, so you can see the order in which stages, when checks and post handlers happen. They are not Jenkins, and they do not parse Groovy.

The skeleton

Every declarative pipeline is one pipeline { ... } block with a handful of allowed sections inside it. A small but complete example:

GROOVY
pipeline {
    agent any

    options {
        timeout(time: 15, unit: 'MINUTES')
        disableConcurrentBuilds()
    }

    environment {
        APP_NAME = 'shop'
    }

    stages {
        stage('Build') {
            steps {
                sh 'npm ci'
                sh 'npm run build'
            }
        }
        stage('Test') {
            steps {
                sh 'npm test'
            }
        }
    }

    post {
        always {
            echo "Finished ${env.APP_NAME}"
        }
    }
}

The sections have fixed meanings:

Section Purpose
agent Where the pipeline (or one stage) runs. Required at the top level.
stages An ordered list of stage blocks. Required.
steps The actual work inside a stage: sh, echo, junit, and so on.
environment Environment variables for the whole pipeline or one stage.
options Pipeline settings such as timeout, retries, build history limits.
parameters Inputs a person supplies when starting a build.
triggers Automatic starts, such as a cron schedule.
when A condition that decides whether a stage runs.
post Handlers that run after the stages, depending on the result.

Declarative syntax is strict on purpose. If you put a section in the wrong place, Jenkins rejects the file before running anything, which catches mistakes early. Inside steps you can use only simple steps; for loops and variables you must open a script { } block (more on that at the end).

agent

The agent directive says where the work happens. agent any means any available agent. Later lessons cover labels and Docker in detail (Agents, Docker Agents and Credentials); for now, know the three most common forms:

GROOVY
agent any                          // any agent
agent { label 'linux' }            // an agent carrying the label "linux"
agent none                         // no agent at top level; each stage chooses its own

environment and options

environment defines variables available to every sh step. Values are strings. You read them in shell as $APP_NAME, and in Groovy as env.APP_NAME. Defined at the top they apply to every stage; defined inside a stage they apply to that stage only.

options change how Jenkins treats the whole run. Three you will use constantly:

  • timeout(time: 15, unit: 'MINUTES') aborts a run that hangs.
  • disableConcurrentBuilds() stops two runs of the same job from overlapping, useful for deployments.
  • buildDiscarder(logRotator(numToKeepStr: '20')) keeps only the latest 20 builds so the disk does not fill up.

parameters and when

parameters lets a person (or an API call) choose values when starting a build:

GROOVY
parameters {
    string(name: 'TARGET', defaultValue: 'staging', description: 'Where to deploy')
    booleanParam(name: 'RUN_SLOW_TESTS', defaultValue: false, description: 'Include slow tests')
    choice(name: 'LOG_LEVEL', choices: ['info', 'debug'], description: 'Verbosity')
}

You read them through the params object: params.TARGET, params.RUN_SLOW_TESTS. A common beginner trap: the "Build with Parameters" form appears only after a first run has registered the parameters with the job, so that first run cannot ask anyone for input.

The when directive makes a stage conditional:

GROOVY
stage('Deploy') {
    when {
        allOf {
            branch 'main'
            expression { params.TARGET == 'production' }
        }
    }
    steps {
        sh './deploy.sh production'
    }
}

Useful built-in conditions include branch, tag, environment, changeset, expression (any Groovy that returns true or false), and the combinators not, allOf and anyOf. When the condition is false the stage is shown as skipped, and the pipeline continues. By default when is evaluated after the stage's agent has been allocated; add beforeAgent true inside when to evaluate it first and avoid grabbing an agent for a stage that will be skipped.

post conditions

The post section is Jenkins' answer to "what should always happen at the end?". It contains named blocks, each guarded by a condition on the result of the run:

Condition Runs when
always Every time, whatever the result
success The run succeeded
failure The run failed
unstable Tests failed but the build compiled (yellow result)
changed The result differs from the previous run
fixed This run succeeded and the previous one did not
cleanup After all the other post blocks, always

post can be placed at the top level or inside a stage. Use it for archiving test reports, stopping containers, and sending notifications. cleanup runs last, which makes it the right place to delete a workspace.

The core behaviour to remember is how failure flows: when a step fails, the stage fails, the remaining stages are skipped, and then post runs with the failure result. Stages never run "in spite of" an earlier failure unless you explicitly say so.

flowchart LR
    A["Build"] --> B["Test"]
    B --> C["Deploy<br/>(when branch is main)"]
    C --> P["post: always, then<br/>success or failure,<br/>then cleanup"]
    B -. "step fails" .-> P

A failing stage skips later stages but never skips the post handlers.

Try it: a pipeline executor

This stand-in takes a plain object that mirrors a declarative pipeline and executes it the way Jenkins orders things: environment first, stages in order, a failure skips the rest, then post handlers (always, then success or failure, then cleanup). Change a step to fail and watch the flow change.

Node.js Execute a model of a declarative pipeline

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.

Real output of that run:

TEXT
[Stage] Build
    Building shop
    + compile
[Stage] Test
    Testing
    + unit-tests
    ERROR: script returned exit code 1 (unit-tests)
[Stage] Deploy: skipped (earlier failure)
[post] result is FAILURE
[post] always
    Archiving reports
[post] failure
    Notify: red
[post] cleanup
    Deleting workspace
Finished: FAILURE

Remove "unit-tests" from the failing set to see the green path: all three stages run, and the success handler fires instead.

Try it: deciding with when

The second stand-in evaluates when conditions the way you read them: branch, expression, not, allOf and anyOf over a context made of the branch name and parameters. The condition tree is plain data, which is also a good mental model for how Jenkins itself treats the directive.

JS Evaluate when conditions

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

No output.

On the context above the output is Build runs, Slow tests skipped, Deploy runs, Preview skipped. Change branch to "feature-x" and the results flip for Deploy and Preview.

When you need Groovy: script blocks

Declarative steps accept only a limited vocabulary. For loops, variables or conditionals inside a stage, wrap the code in script { }:

GROOVY
steps {
    script {
        def targets = ['eu', 'us']
        targets.each { t -> echo "Deploying to ${t}" }
    }
}

Keep these blocks small. A pipeline that is mostly script is a scripted pipeline in disguise, and loses the checks that make declarative syntax pleasant. Move heavy logic into shell scripts in your repository or into a shared library.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A step in the Test stage fails. What happens to the Deploy stage that comes after it, and to the post section?

    A failed stage skips the remaining stages, but post exists precisely to run afterwards, so always and failure still fire.
  2. 2. Which post block runs after all of the other post blocks?

    cleanup is guaranteed to run last, which makes it the right place to delete workspaces or temporary files.
  3. 3. How do you read a pipeline parameter named TARGET inside Groovy code?

    Parameters are exposed on the params object. They are also available as environment variables inside sh steps.
  4. 4. What does adding beforeAgent true to a when block change?

    By default the stage's agent is allocated first. With beforeAgent true a skipped stage never occupies an executor.

Summary

  • A declarative Jenkinsfile is one pipeline { } block with fixed sections: agent, stages, steps, environment, options, parameters, when and post.
  • A failing stage skips the remaining stages; post handlers still run (always, then result-based ones, then cleanup).
  • when makes stages conditional and can combine branch, expression, not, allOf and anyOf.
  • parameters appear as params.NAME; the input form shows up only after the first run has registered them.
  • Use script { } sparingly for Groovy logic; keep the pipeline mostly declarative.

Next: Scripted Pipelines and Shared Libraries.