如何在 Jenkins 管道 Jenkinsfile 中正确编写关于 BooleanParameter 的 if 语句?

How to write properly an if statement in regards to a BooleanParameter in Jenkins pipeline Jenkinsfile?

我正在设置 Jenkins 管道 Jenkinsfile,我想检查是否设置了布尔参数。

这是文件的相关部分:

node ("master") {
        stage 'Setup' (
                [[$class: 'BooleanParameterValue', name: 'BUILD_SNAPSHOT', value: 'Boolean.valueOf(BUILD_SNAPSHOT)']],

据我所知,这是访问布尔参数的方式,但我不确定如何陈述 IF 语句本身。

我正在考虑做类似的事情:

if(BooleanParameterValue['BUILD_SNAPSHOT']){...

请问这条语句的正确写法是什么?

答案实际上比这简单得多! 根据 pipeline documention,如果你定义了一个布尔参数 isFoo,你可以在你的 Groovy 中访问它,只需要它的名字,所以你的脚本实际上看起来像:

node {
   stage 'Setup'
   echo "${isFoo}"   // Usage inside a string
   if(isFoo) {       // Very simple "if" usage
       echo "Param isFoo is true"
       ...
   }
}

顺便说一下,您可能不应该调用您的参数 BUILD_SNAPSHOT,但也许应该调用 buildSnapshotisBuildSnapshot,因为它是一个参数而不是常量。

只是做 if(isFoo){...} 并不能保证它正常工作:) 为了安全起见,请使用 if(isFoo.toString()=='true'){ ... }

您的管道脚本可以通过 3 种方式访问​​布尔参数:

  1. 作为一个裸参数,例如:isFoo

  2. 来自 env 地图,例如:env.isFoo

  3. 来自 params 地图,例如:params.isFoo

如果您使用 1) 或 2) 访问 isFoo,它将有一个字符串值(“true”或“false”)。

如果您使用 3) 访问 isFoo,它将有一个布尔值。

因此,在您的脚本中测试 isFoo 参数的最简单的方法 (IMO) 是这样的:

if (params.isFoo) {
   ....
}

或者你可以这样测试:

if (isFoo.toBoolean()) {
   ....
}​​​​​​​​​​​​​​​​​​

if (env.isFoo.toBoolean()) {
   ....
}​​​​​​​​​​​​​​​​​​

toBoolean() 需要将 "true" 字符串转换为布尔值 true 并将 "false" 字符串转换为布尔值 false.