Your first declarative pipeline

Jenkins · Essentials · 12 min

Declarative pipeline syntax is how almost all new Jenkins jobs are written.

A declarative pipeline is a structured Groovy DSL. The skeleton is always:

  • pipeline { }: the root block.
  • agent: where to run. agent any means any available executor; later you will use labels and containers.
  • stages { stage('Name') { steps { ... } } }: named phases shown as columns in the UI.
  • steps: the actual work, using steps such as sh (shell on Unix), bat or powershell (Windows), echo, git, archiveArtifacts and junit.

sh fails the stage and the build if the command exits non-zero, and later stages are skipped. Multi-line shell scripts use triple quotes '''...'''.

Quoting matters because this is Groovy: in double-quoted strings Groovy interpolates ${...} before the shell sees the text; in single-quoted strings the shell does the expansion. Use single quotes unless you need a Groovy value.

To try it, create a Pipeline job, choose Pipeline script and paste the code. The Snippet Generator (Pipeline Syntax link on the job) produces correct syntax for any installed step, and Replay lets you edit and rerun a build's script without committing, ideal while learning.

Example

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo "Building #${env.BUILD_NUMBER}"   // Groovy interpolation
                sh '''
                    mkdir -p out
                    echo "built at $(date -u)" > out/info.txt
                '''
            }
        }
        stage('Test') {
            steps {
                sh 'test -s out/info.txt && echo OK'      // OK
            }
        }
    }
}

Remember

  • pipeline > agent + stages > stage > steps
  • sh fails the build on a non-zero exit code
  • Single quotes: shell expands; double quotes: Groovy interpolates first

Watch out for

  • Using double quotes around shell commands containing $ and getting Groovy errors or wrong values.

Check yourself

  1. In sh "echo ${HOME}", who expands ${HOME}?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: www.jenkins.io/doc/book/pipeline/syntax/