首页 > 解决方案 > Jenkins 管道可选布尔参数

问题描述

我正在尝试使用具有可以覆盖的默认布尔值的自定义函数。问题是它不会覆盖默认值。所有迭代都匹配“else”。

pipeline {

  agent {
    label 'any'
  }

  stages {
    stage('Foo') {
      steps {
        doThing('/opt/prod','athos',true)
        doThing('/opt/demo','aramis',true)
        doThing('/opt/test','porthos')
        doThing('/opt/dev','dartagnan')
      }
    }
  }
}

def doThing(def targetDir, def stackName, def prod=false) {
  if ( env.prod == true ) {
    sh """
      execute-bin \
        -Dbin.target=${targetDir} \
        -Dbin.stackName=${stackName} \
        -Dbin.prod=true
    """
  } else {
    sh """
      execute-bin \
        -Dbin.target=${targetDir} \
        -Dbin.stackName=${stackName}
    """
  }
}

标签: jenkinsjenkins-pipeline

解决方案


尝试比较字符串值:

  if ( prod == 'true' ) 

发生这种情况是因为环境变量始终是字符串,并且没有 qoutes 的 true 是布尔值,因此它永远不等于:

考虑一下:

def doThing(def prod=false) {
  if ( prod == true ) {
    println 'TRUE'   
  } else {
    println 'FALSE'
  }
}

// this is how environment are passed into the pipeline from jenkins UI
doThing('true')
> FALSE
doThing('false')
> FALSE

// if environment variables were boolean (and they are not) it would be ok
doThing(true)
> TRUE
doThing(false)
> FALSE

// the current equality check is always false
println true=='true'
> false
println true=='false'
> false

推荐阅读