Skip to main content

Creating Declarative Pipelines

1. Defining Pipeline Block

Property Values Description
pipeline pipeline { ... } Defines the declarative pipeline block

Example: Basic Pipeline Definition

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo 'Building...'
            }
        }
    }
}

2. Configuring Agent Directive

Property Values Description
agent none, any, docker, dockerfile, label, node Specifies where and how to run the pipeline or stage
agent.none none No agent is allocated; stages must be run on a node defined in the stage
agent.any any Allocates any available agent from the pool
agent.label label Allocates an agent with the specified label
agent.docker docker { image 'node:16' } Runs the pipeline or stage in a Docker container
agent.dockerfile dockerfile true Uses a Dockerfile in the workspace to build and run the container
agent.node node { label 'my-node' } Allocates a specific node or node with matching label

Example: Using Docker Agent

pipeline {
    agent {
        docker {
            image 'node:16'
            args '-v /tmp:/tmp'
        }
    }
    stages {
        stage('Build') {
            steps {
                sh 'npm install'
            }
        }
    }
}

Example: Using Label Agent

pipeline {
    agent {
        label 'production'
    }
    stages {
        stage('Deploy') {
            steps {
                sh 'echo "Deploying to production"'
            }
        }
    }
}

3. Using Stages and Steps

Stage/Step Description Example
stage Defines a distinct phase in the pipeline execution
stage('Build') {
    steps {
        sh 'make'
    }
}
steps Contains a list of steps to execute within a stage
steps {
    sh 'echo "Building..."'
}
sh Executes shell commands on the agent sh 'ls -la'
script Allows Groovy code execution inside a stage
script {
    def buildNumber = "BUILD-${env.BUILD_NUMBER}"
    echo "Building version ${buildNumber}"
}
parallel Runs multiple stages in parallel
parallel (
    stage1: {
        steps { sh 'echo "Running stage 1"' }
    },
    stage2: {
        steps { sh 'echo "Running stage 2"' }
    }
)

Example: Building a Multi-Stage Pipeline

pipeline {
    agent any
    stages {
        stage('Checkout') {
            steps {
                git branch: 'main', url: 'https://github.com/example/repo.git'
            }
        }
        stage('Build') {
            steps {
                sh 'make'
            }
        }
        stage('Test') {
            steps {
                sh 'make test'
            }
        }
        stage('Deploy') {
            steps {
                sh 'make deploy'
            }
        }
    }
}
Note: Stages and steps are the core building blocks of Jenkins Declarative Pipelines. Each stage can contain multiple steps, and steps are the actual actions performed within a stage.

4. Setting Environment Variables

Property Values Description
environment key: value Defines environment variables for the pipeline or stage
environment key: value Values can reference other environment variables using $VAR_NAME

Example: Setting Environment Variables

pipeline {
    agent any
    environment {
        DB_URL = 'jdbc:postgresql://localhost:5432/mydb'
        DB_USER = 'admin'
        DB_PASSWORD = credentials('db-password')
    }
    stages {
        stage('Build') {
            steps {
                sh 'echo "Connecting to $DB_URL with user $DB_USER"'
            }
        }
    }
}

Example: Using Environment Variables in Script

pipeline {
    agent any
    environment {
        PROJECT_NAME = 'my-project'
        BUILD_NUMBER = env.BUILD_NUMBER
    }
    stages {
        stage('Deploy') {
            steps {
                sh "echo 'Deploying ${PROJECT_NAME} build ${BUILD_NUMBER}'"
            }
        }
    }
}

5. Using Parameters Directive

Parameter Type Description Default Value
name string Name of the parameter N/A
default string Default value for the parameter Empty string
description string Description of the parameter Empty string
options list List of valid options for choice parameters None

Example: Declaring Parameters

pipeline {
    agent any
    parameters {
        string(name: 'BUILD_NAME', defaultValue: 'default-build', description: 'Name of the build')
        booleanParam(name: 'DEBUG_MODE', defaultValue: false, description: 'Enable debug mode')
        choice(name: 'ENVIRONMENT', choices: ['dev', 'staging', 'prod'], description: 'Target environment')
    }
    stages {
        stage('Build') {
            steps {
                echo "Building ${params.BUILD_NAME} in ${params.ENVIRONMENT} with debug: ${params.DEBUG_MODE}"
            }
        }
    }
}
Note: Parameters can be accessed within the pipeline using params.<parameterName>.
Warning: Parameter names must be unique within the pipeline and should not contain spaces or special characters.

6. Using Triggers Directive

Trigger Description Parameters Example
pollSCM Triggers the build at regular intervals by polling the SCM pollSCM('H/15 * * * *')
triggers {
    pollSCM('H/15 * * * *')
}
upstream Triggers the build when an upstream project completes successfully upstream('project-name')
triggers {
    upstream('build-project')
}
githubPush Triggers the build on a push to a GitHub repository githubPush()
triggers {
    githubPush()
}
upstreamBuild Triggers the build when an upstream project completes with a specific result upstreamBuild('project-name', 'SUCCESS')
triggers {
    upstreamBuild('build-project', 'SUCCESS')
}
remoteTrigger Triggers the build when a remote Jenkins job completes remoteTrigger('job-name')
triggers {
    remoteTrigger('remote-job')
}

Example: Polling SCM

pipeline {
    agent any
    triggers {
        pollSCM('H/15 * * * *')
    }
    stages {
        stage('Build') {
            steps {
                echo 'Building...'
            }
        }
    }
}

Example: GitHub Push Trigger

pipeline {
    agent any
    triggers {
        githubPush()
    }
    stages {
        stage('Build') {
            steps {
                echo 'Building on GitHub push...'
            }
        }
    }
}

7. Configuring Options

Option Description Default Value Notes
agent Specifies where the pipeline will run any Can be none, any, or a specific agent definition
stages Contains the stages to be executed in the pipeline Required Must contain at least one stage
post Defines actions to be executed after the pipeline completes never Can be always, unstable, failure, or success
parameters Defines parameters that can be passed to the pipeline [] Can include string, boolean, and choice types
triggers Defines when the pipeline should be triggered [] Can include upstream, pollSCM, and githubPush
tools Defines tools to be used in the pipeline (e.g., JDK, Maven) [] Can specify tool versions and names
environment Defines environment variables for the pipeline [] Can include key-value pairs for environment variables
options Defines pipeline options such as build discarders and timeout [] Can include buildDiscarder, disableConcurrentBuilds, and timeout

Example: Defining Pipeline Options

pipeline {
    agent any
    options {
        buildDiscarder logRotator(daysToKeepStr: '14', numToKeepStr: '5')
        disableConcurrentBuilds()
        timeout(time: 1, unit: 'HOURS')
    }
    stages {
        stage('Build') {
            steps {
                echo 'Building...'
            }
        }
    }
}

8. Using Tools Directive

Tool Version Installation Usage
nodejs 18.17.0 Installed via Jenkins Tool Installer tools { nodejs 'nodejs-18.17.0' }
maven 3.9.4 Installed via Jenkins Tool Installer tools { maven 'maven-3.9.4' }
gradle 8.1.1 Installed via Jenkins Tool Installer tools { gradle 'gradle-8.1.1' }

Example: Using Node.js in Pipeline

pipeline {
    agent any
    tools {
        nodejs 'nodejs-18.17.0'
    }
    stages {
        stage('Build') {
            steps {
                sh 'node --version'
            }
        }
    }
}

Example: Using Maven in Pipeline

pipeline {
    agent any
    tools {
        maven 'maven-3.9.4'
    }
    stages {
        stage('Build') {
            steps {
                sh 'mvn --version'
            }
        }
    }
}

9. Defining Post Actions

Post actions in Jenkins declarative pipelines are executed after the main pipeline execution completes, regardless of whether it succeeded or failed. They are useful for cleanup, notifications, or archiving artifacts.

Action Description Usage Example
always Executes regardless of pipeline outcome.
post {
  always {
    echo 'Pipeline completed'
  }
}
success Executes only if the pipeline completes successfully.
post {
  success {
    echo 'Pipeline succeeded'
  }
}
failure Executes only if the pipeline fails.
post {
  failure {
    echo 'Pipeline failed'
  }
}
unstable Executes if the pipeline completes but is marked as unstable (e.g., tests fail but build continues).
post {
  unstable {
    echo 'Pipeline is unstable'
  }
}
aborted Executes if the pipeline was aborted by a user or timeout.
post {
  aborted {
    echo 'Pipeline was aborted'
  }
}

Example: Post Actions with Artifact Archiving

pipeline {
  agent any
  stages {
    stage('Build') {
      steps {
        echo 'Building...'
      }
    }
  }
  post {
    success {
      archiveArtifacts artifacts: 'build/*.jar', fingerprint: true
    }
    failure {
      mail to: 'team@example.com', subject: 'Build Failed', body: 'The build has failed.'
    }
  }
}

10. Using When Conditions

When conditions in Jenkins declarative pipelines allow you to control whether a stage or block of steps should run based on specific criteria. These conditions are evaluated at runtime and can be used to make pipeline execution dynamic.

Condition Description Example
branch Runs the stage only when the branch name matches the specified value.
when {
    branch 'main'
}
environment Runs the stage only when an environment variable matches a specified value.
when {
    environment name: 'ENV', value: 'production'
}
equals Runs the stage only when two values are equal.
when {
    equals expected: 'release', actual: env.BRANCH_NAME
}
not Negates a condition. Runs the stage if the inner condition is false.
when {
    not {
        branch 'develop'
    }
}
anyOf Runs the stage if any of the provided conditions are true.
when {
    anyOf {
        branch 'main'
        branch 'release'
    }
}
allOf Runs the stage only if all provided conditions are true.
when {
    allOf {
        branch 'main'
        environment name: 'ENV', value: 'production'
    }
}

Example: Using when with environment variable

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo 'Building...'
            }
        }
        stage('Deploy') {
            when {
                environment name: 'ENV', value: 'production'
            }
            steps {
                echo 'Deploying to production...'
            }
        }
    }
}

Example: Using when with branch and environment

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo 'Building...'
            }
        }
        stage('Deploy to Staging') {
            when {
                allOf {
                    branch 'staging'
                    environment name: 'ENV', value: 'staging'
                }
            }
            steps {
                echo 'Deploying to staging...'
            }
        }
    }
}

Was this article helpful?