Jenkins Pipeline stage skip based on groovy variable defined in pipeline

柔情痞子 提交于 2020-08-27 21:41:50

问题


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}"
             // Perform some action
        }
    }

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


回答1:


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

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

Source



来源:https://stackoverflow.com/questions/57602609/jenkins-pipeline-stage-skip-based-on-groovy-variable-defined-in-pipeline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!