Search code examples
jenkinsgroovyjenkins-pipelinecontinuous-deploymentjenkins-groovy

Jenkins Pipeline stage skip based on groovy variable defined in pipeline


I'm trying to skip a stage based a groovy variable and that variable value will be calculated in another stage.

In the below example, Validate stage is conditionally skipped based Environment variable VALIDATION_REQUIRED which I will pass while building/triggering the Job. --- This is working as expected.

Whereas the Build stage always runs even though isValidationSuccess variable is set as false. I tried changing the when condition expression like { return "${isValidationSuccess}" == true ; } or { return "${isValidationSuccess}" == 'true' ; } but none worked. When printing the variable it shows as 'false'

def isValidationSuccess = true 
 pipeline {
    agent any
    stages(checkout) {
        // GIT checkout here
    }
    stage("Validate") {
        when {
            environment name: 'VALIDATION_REQUIRED', value: 'true'
        }
        steps {
            if(some_condition){
                isValidationSuccess = false;
            }
        }
    }
    stage("Build") {
        when {
            expression { return "${isValidationSuccess}"; }
        }
        steps {
             sh "echo isValidationSuccess:${isValidationSuccess}"
        }
    }
 }
  1. At what phase does the when condition will be evaluated.
  2. Is it possible to skip the stage based on the variable using when?
  3. Based on a few SO answers, I can think of adding conditional block as below, But when options look clean approach. Also, the stage view shows nicely when that particular stage is skipped.
script {
      if(isValidationSuccess){
             // Do the build
       }else {
           try {
             currentBuild.result = 'ABORTED' 
           } catch(Exception err) {
             currentBuild.result = 'FAILURE'
           }
           error('Build not happened')
       }
}

References: https://jenkins.io/blog/2017/01/19/converting-conditional-to-pipeline/


Solution

  • stage("Build") {
            when {
                expression { isValidationSuccess == true }
            }
            steps {
                 // do stuff
            }
        }
    

    when validates boolean values so this should be evaluate to true or false.

    Source