A Jenkins stage refers to a phase in a Jenkins Pipeline. Stages allow us to group a series of tasks in a single entity and reference them under a unique identifier. Using Jenkins stages, we can visualize and track the progress of the pipeline build using the specified identifier. It can also help us track the errors in the logs.
For example, we can have a pipeline with three stages: Build, Test, and Deploy. Each stage contains one or more tasks needed to complete the set tasks. For example, in the build stage, we can have tasks such as installing the necessary dependencies, setting up the directories, etc.
In the testing stage, we can run the tests which are required for that project and publish the test results using tools such as HTML reports, cucumber, etc.
Finally, in the deployment stage, we can have the tasks such as logging into a remote server, executing a setup script, and other steps.
When we run the pipeline, Jenkins executes the tasks in each stage in the order in which they are defined to completion. If one of the steps in a given stage fails, the entire build fails and no other stages are executed.
Jenkins Stage Block
In a Jenkinsfile, we can define the stages using the Stages and stage block. The stages block allows us to tell Jenkins that the upcoming blocks contain the stages that we wish to execute in the build.
We then use the stage block to define a distinct set of tasks which are executed in the pipeline.
An example syntax is as follows:
agent any
stages {
stage('Build') {
steps {
// tasks to run goes here
}
}
stage('Test') {
steps {
// testing tasks
}
}
stage('Deploy') {
steps {
// deployment tasks
}
}
}
}
Each stage must contain one or more steps which are the individual tasks that are executed in the context of the stage. For example, you can define the steps using one of the available step functions such as sh to execute a shell command, a Groovy script, or git to run a Git command.
You can check the documentation and plugin support to learn the capabilities of Jenkins.
Example:
The following example shows a simple pipeline with a single stage:
agent any
stages {
stage('Version') {
steps {
script {
def jenkinsVersion = hudson.model.Hudson.instance.version
println "Jenkins version: ${jenkinsVersion}"
}
}
}
}
}
The previous pipeline defines a single stage called “Version” which contains a single step that executes a Groovy script. The script uses the hudson.model.Hudson class to get the Jenkins version and print it using the println function.
Once we run the previous pipeline, we should see the installed Jenkins version in the console output.
Conclusion
This post covers on how to create and use the stages in a Jenkins pipeline. Stages allow us to group the tasks under a single entity for easier management and tracking.