7

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?

Bruce Becker
  • 3,783
  • 4
  • 20
  • 41

1 Answers1

7

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'
            }
        }
    }
}
Bruce Becker
  • 3,783
  • 4
  • 20
  • 41
Hedi Nasr
  • 746
  • 3
  • 7