How to check if build parameter is available in Jenkinsfile

拥有回忆 提交于 2019-12-13 11:40:58

问题


I have a pipeline script that should work with and without parameters. So I have to check if the parameter is available.

I tried if(getBinding().hasVariable("myparameter")) but this leads to an Exception

org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use method groovy.lang.Binding getVariables

Is there another way to check if the job is parameterized?


回答1:


Newer versions make the parameters available through the params variable. If the parameter is not defined, it falls back to the configured default (see also here).




回答2:


In the latest version of jenkins println(getBinding().hasVariable("myparameter")) is permitted and does not give an error any more.




回答3:


This is how I did that:

def myParam = false
if (params.myParam != null){
    myParam = params.myParam
}

Why do that at all when you can just define parameters in your pipeline as suggested above?

Well, there are situations when you want your pipeline file to work regardless of if parameter is defined or not. I.e., if you're re-using your pipeline script from different Jenkins jobs and you don't want to make people define that parameter ...




回答4:


See Getting Started with Pipeline, Build Parameters:

Build Parameters

If you configured your pipeline to accept parameters using the Build with Parameters option, those parameters are accessible as Groovy variables of the same name.

UPDATE

  • This build is parameterizedAdd parameterString Parameter:

    • Name: STRING_PARAMETER
    • Default Value: STRING_PARAMETER_VALUE
  • PipelineDefinition: Pipeline scriptScript:

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"

Console Output:

[Pipeline] echo
  STRING_PARAMETER=STRING_PARAMETER_VALUE
[Pipeline] echo
  stringParameterExists=true
[Pipeline] echo
  otherParameterExists=false
[Pipeline] End of Pipeline
Finished: SUCCESS


来源:https://stackoverflow.com/questions/38145508/how-to-check-if-build-parameter-is-available-in-jenkinsfile

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