HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Jenkins Declarative pipeline: Execute stage conditional on execution of previous stage

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
declarativepreviousjenkinsconditionalexecutionstagepipelineexecute

Problem

I have a Jenkins declarative pipeline with several stages. Some of these stages need to be executed based on whether a previous stage has been executed. In pseudocode:

pipeline{
  stages{
    stage('1: Always do this thing') {
      steps { 
        sh 'do_thing.sh'
      } 
    }
    stage('2: Maybe do this thing') {
      when{ condition }
      steps {
        sh 'sometimes_do_this_thing.sh'
      }
    }
    stage('3: Do this thing if 2 was executed'){
      when { pipeline.stages.2.was_executed }
      steps {
        sh 'conditional_path.sh'
      }
    }
  }
}


I accept that the best way to do this might be in the scripted pipeline, but I have declarative pipelines. Including some scripted bits in them is also acceptable, if kept to a minimum.

So: What is the most elegant way to execute a stage in a pipeline conditional on the execution status of the previous one?

Solution

A pretty simple solution is to declare a global variable on top of your pipeline, and check it's value in your last conditional stage:

def flag = false;

pipeline {
stages {
stage('1 - Always') {
steps {
sh './always.sh'
}
}

stage('2 - Maybe') {
when { condition }

steps {
sh './maybe.sh'
script { flag = true }
}
}

stage('3 - If Maybe was executed') {
when { expression { flag == true } }

steps {
sh './conditional.sh'
}
}
}
}

Context

StackExchange DevOps Q#9816, answer score: 7

Revisions (0)

No revisions yet.