How do we get the status of the preceding stage(s) in a Jenkins pipeline. For example: My example pipeline is as under:
pipeline {
agent
{
node {
label 'master'
customWorkspace "${env.JobPath}"
}
}
stages
{
stage('Start') {
steps {
sh 'ls'
}
}
stage ('set_env') {
steps {
// script to set environment.
}
}
stage ('Build') {
steps {
// script to build.
}
}
stage ('Send_mail') {
steps {
// script to send mail.
}
}
stage('End') {
steps {
sh 'ls'
}
}
}
}
How can i get the status of a particular stage in a pipeline. for ex: i want to take certain decisions based on whether the "Build" stage was a success or a failure.
Is there any environment variable which tracks the status of every stage, or there's a Jenkins REST API which can help me achieve this.
Thanks!
Jenkins declarative pipelines are opinionated syntax on top of the former jenkins pipeline approach. This means you can also regard a jenkins declarative pipeline as a groovy script with extra syntactic sugar. So you can freely use variables. As mentioned in my comment above, you can set the whole jobs status via currentBuild.result
, but if you want to make decisions within the same job between stages: simply use groovy variables to indicate the state of the previous stage. Taking your example:
pipeline {
def didSucceed = true
agent
{
node {
label 'master'
customWorkspace "${env.JobPath}"
}
}
stages
{
stage('Start') {
steps {
sh 'ls'
}
}
stage ('set_env') {
steps {
// script to set environment.
didSucceed = true // Here you indicate whether stuff actually worked..
}
}
stage ('Build') {
steps {
if (didSucceed) {
// script to build.
} else {
// Procedure in case of previous error..
}
}
}
stage ('Send_mail') {
steps {
// script to send mail.
}
}
stage('End') {
steps {
sh 'ls'
}
}
}
}
You could also stay in a more declarative way using the when statement in combination with a boolean variable.