如何检查Jenkinsfile中是否有可用的构建参数

dom*_*ruf 8 jenkins jenkins-pipeline

我有一个管道脚本,可以使用和不使用参数.所以我必须检查参数是否可用.

我试过if(getBinding().hasVariable("myparameter"))但这会导致异常

org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use method groovy.lang.Binding getVariables
Run Code Online (Sandbox Code Playgroud)

有没有其他方法来检查作业是否参数化?

Ste*_*ven 8

在最新版本的jenkins中println(getBinding().hasVariable("myparameter"))是允许的,不再出错.

  • 您能否更新一下在您撰写本文时哪个版本是最新版本? (4认同)

Ger*_*ica 6

请参阅流水线入门,构建参数

构建参数

如果您使用Build with Parameters选项将管道配置为接受参数,则这些参数可作为同名的 Groovy 变量访问。

更新

  • ? 这个构建是参数化的Add parameter? 字符串参数

    • 姓名:STRING_PARAMETER
    • 默认值STRING_PARAMETER_VALUE
  • 管道? 定义Pipeline script脚本

def stringParameterExists = true
def otherParameterExists = true

try {
  println "  STRING_PARAMETER=$STRING_PARAMETER"
  }
catch (MissingPropertyException e) {
  stringParameterExists = false
  }  

try {
  println "  NOT_EXISTING_PARAMETER=$NOT_EXISTING_PARAMETER"
  }
catch (MissingPropertyException e) {
  otherParameterExists = false
  }

println "  stringParameterExists=$stringParameterExists"
println "  otherParameterExists=$otherParameterExists"
Run Code Online (Sandbox Code Playgroud)

控制台输出:

[Pipeline] echo
  STRING_PARAMETER=STRING_PARAMETER_VALUE
[Pipeline] echo
  stringParameterExists=true
[Pipeline] echo
  otherParameterExists=false
[Pipeline] End of Pipeline
Finished: SUCCESS
Run Code Online (Sandbox Code Playgroud)


Ste*_*ing 5

较新的版本通过params变量使参数可用。如果未定义该参数,则它会回退到配置的默认值(另请参阅此处)。


小智 5

这是我这样做的方式:

def myParam = false
if (params.myParam != null){
    myParam = params.myParam
}
Run Code Online (Sandbox Code Playgroud)

当您只需要按照上述建议在管道中定义参数时,为什么要这么做呢?

好吧,在某些情况下,无论是否定义参数,都希望管道文件可以工作。也就是说,如果您要重新使用来自其他Jenkins作业的管道脚本,而又不想人们定义该参数,则...