Jenkins Declarative Pipeline syntax

The Jenkins Declarative Pipeline provides a structured and readable syntax for defining and managing pipelines in Jenkins. It offers a way to represent our Pipeline as code, making it easier to understand, maintain, and collaborate. Let us explore the critical components of the Declarative Pipeline syntax.

Pipeline block

At the core of the Declarative Pipeline is the Pipeline block. This block encapsulates the entire Pipeline configuration and serves as the entry point for our Pipeline definition.

pipeline {
// Pipeline configuration goes here
}

Agent block

We can specify the agent block inside the Pipeline block to define where the pipeline should run. It determines the execution environment for our pipeline, such as a specific agent or a Docker container.

pipeline {
agent {
// Define the agent configuration here
}
// Rest of the pipeline definition
}

Stages block

The stages block allows us to define the different stages of our pipeline. Each stage represents a different build, test, or deployment phase. We can have as many stages as needed, and they can be executed sequentially or in parallel.

pipeline {
// ...
stages {
stage('Build') {
// Steps for the Build stage go here
}
stage('Test') {
// Steps for the Test stage go here
}
// Add more stages as required
}
// ...
}

Steps block

We can define steps representing the individual actions or tasks within each stage. Steps can be predefined, custom, or even called external scripts or functions.

pipeline {
// ...
stages {
stage('Build') {
steps {
// Predefined steps (e.g., shell commands, file operations)
sh 'mvn clean package'
// Custom steps (e.g., function calls, script execution)
script {
customBuildStep()
}
// Calling other scripts or functions
script {
sh './path/to/other/script.sh'
}
}
}
// ...
}
// ...
}

Post actions

After all the stages have been completed, we can define post actions to perform specific tasks based on the outcome of the Pipeline. For example, we can define actions for success, failure, or actions that should always be performed.

pipeline {
// ...
post {
success {
// Actions to perform if the pipeline succeeds
}
failure {
// Actions to perform if the pipeline fails
}
always {
// Actions to always perform, regardless of the pipeline status
}
}
}

Environment

The environment block allows us to define environment variables accessible across stages and steps. It can help set up necessary configurations or pass data between different parts of our Pipeline.

pipeline {
// ...
environment {
VARIABLE_NAME = 'value'
// Define more environment variables as needed
}
// ...
}

By following the structured syntax of the Jenkins Declarative Pipeline, we can define our Pipelines in a more organized and maintainable way. This syntax lets us clearly define stages, steps, and post actions, which makes it easier to understand and collaborate on complex Pipeline configurations.

Copyright ©2024 Educative, Inc. All rights reserved