6

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?

2
  • Could you explain what is going wrong? What I see on a daily basis is that if one uses stage that they are executed sequentially and the next stage will be started if the former has been completed, unless if parallel is enabled.
    – 030
    Nov 15, 2019 at 9:27
  • The issue is only that I can't predict whether the condition will be satisfied in Stage 2. I don't want to set up conditions based on the commit or message, but on the state of stages in the pipeline. Sequential execution is fine, but some stages should be skipped in some cases. Nov 15, 2019 at 9:50

1 Answer 1

6

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'
            }
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.