I have a Jenkins global variable in a string - how do I evaluate it?

99封情书 提交于 2019-12-23 04:47:11

问题


I need to accept all kinds of global Jenkins variables as strings (basically as parameters to ansible like system - a template stored in \vars).

def proof = "\"${params.REPOSITORY_NAME}\""
echo proof 
def before = "\"\${params.REPOSITORY_NAME}\""
echo before
def after = Eval.me(before)
echo after

The result is:

[Pipeline] echo
"asfd"
[Pipeline] echo
"${params.REPOSITORY_NAME}"

groovy.lang.MissingPropertyException: No such property: params for class: Script1
  • the first echo proves that the param value actually exists.
  • the second echo is the what the input actually looks like.
  • the third echo should have emitted asdf instead I get the exception.

Any ideas? I'm hours into this :-(


回答1:


You may want to check: groovy: Have a field name, need to set value and don't want to use switch

1st Variant

In case you have: xyz="REPOSITORY_NAME" and want the value of the parameter REPOSITORY_NAME you can simply use:

def xyz = "REPOSITORY_NAME"
echo params."$xyz" // will print the value of params.REPOSITORY_NAME

In case if your variable xyz must hold the full string including params. you could use the following solution

@NonCPS
def split(string) {
    string.split(/\./)
}

def xyz = "params.REPOSITORY_NAME"

def splitString = split(xyz)
echo this."${splitString[0]}"."${splitString[1]}"  // will print the value of params.REPOSITORY_NAME

2nd Variant

In case you want to specify an environment variable name as parameter you can use:

 env.“${params.REPOSITORY_NAME}”

In plain groovy env[params.REPOSITORY_NAME] would work but in pipeline this one would not work inside the sandbox.

That way you first retrieve the value of REPOSITORY_NAME and than use it as key to a environment variable.

Using directly env.REPOSITORY_NAME will not be the same as it would try to use REPOSITORY_NAME itself as the key.

E.g. say you have a job named MyJob with the following script:

assert(params.MyParameter == "JOB_NAME")
echo env."${params.MyParameter}"
assert(env."${params.MyParameter}" == 'MyJob')

This will print the name of the job (MyJob) to the console assuming you did set the MyParameter parameter to JOB_NAME. Both asserts will pass.

Please don’t forget to open a node{} block first in case you want to retrieve the environment of that very node.




回答2:


After trying all those solutions, found out that this works for my problem (which sounds VERY similar to the question asked - not exactly sure though):

${env[REPOSITORY_NAME]}



来源:https://stackoverflow.com/questions/51333763/i-have-a-jenkins-global-variable-in-a-string-how-do-i-evaluate-it

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