【问题标题】:Jenkins Pipeline stage skip based on groovy variable defined in pipelineJenkins Pipeline阶段跳过基于管道中定义的groovy变量
【发布时间】:2020-11-02 04:17:22
【问题描述】:

我正在尝试跳过基于 groovy 变量的stage,该变量值将在另一个阶段计算。

在下面的示例中,Validate 阶段基于环境变量VALIDATION_REQUIRED 有条件地跳过,我将在构建/触发作业时通过它。 --- 这是按预期工作的。

Build 阶段始终运行,即使isValidationSuccess 变量设置为false。 我尝试更改when 条件表达式,如{ return "${isValidationSuccess}" == true ; }{ return "${isValidationSuccess}" == 'true' ; },但没有一个起作用。 打印变量时,它显示为“假”

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. 将在哪个阶段评估 when 条件。
  2. 是否可以根据使用when的变量跳过阶段?
  3. 基于一些 SO 答案,我可以考虑添加如下条件块,但 when 选项看起来很干净。此外,当跳过特定阶段时,stage view 也能很好地显示。
script {
      if(isValidationSuccess){
             // Do the build
       }else {
           try {
             currentBuild.result = 'ABORTED' 
           } catch(Exception err) {
             currentBuild.result = 'FAILURE'
           }
           error('Build not happened')
       }
}

参考资料: https://jenkins.io/blog/2017/01/19/converting-conditional-to-pipeline/

【问题讨论】:

  • 为什么在when 中使用return?你试过when { expression { isValidationSuccess == true } } 吗?
  • 这行得通。谢谢。
  • 好的,太好了!我会将其发布为答案,以便人们更清楚地看到解决方案。

标签: jenkins groovy jenkins-pipeline continuous-deployment jenkins-groovy


【解决方案1】:
stage("Build") {
        when {
            expression { isValidationSuccess == true }
        }
        steps {
             // do stuff
        }
    }

when 验证布尔值,因此这应该被评估为真或假。

Source

【讨论】: