Home > Mobile >  jenkins groovy: evaluate a string
jenkins groovy: evaluate a string

Time:12-13

I need to reproduce the following Python code in jenkins groovy

city='Petersburg'
varname='city'
varvalue=eval(varname)
print(varvalue) # prints 'Petersburg'

that is i need to assign the value of a variable to another variable knowing the name of the source variable as a string.

Please provide the same code written in jenkins groovy (which I can insert into a Jenkinsfile)

SUPPLEMENTARY DETAILS

based on this post I tried groovy eval class:

city='Petersburg'
varname='city'
varvalue=Eval.me(varname)
println(varvalue)

it output the following error in jenkins console output:

hudson.remoting.ProxyException: org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Script1.groovy: 1: expecting ''', found '<EOF>' @ line 1, column 15.
   varvalue='city

I also tried the following code (using groovy Eval as Python exec):

city='Petersburg'
varname='city'
Eval.me('varvalue=\''   varname)
println(varvalue)

whitch produced the same error:

hudson.remoting.ProxyException: org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Script1.groovy: 1: expecting ''', found '<EOF>' @ line 1, column 15.
   varvalue='city

CodePudding user response:

The Eval.me function evaluates the script in a separated execution context and therefore cannot access the variables you defined before accessing it (See Eval Documentation).
So to use it you will have to pass the binding of the parameters so it will recognize it, something like:

city='Petersburg'
varname='city' 
varvalue=Eval.me('city', 'Petersburg', varname)
println(varvalue)​

But passing the parameter bindings probably contradicts what you are trying to achieve, so instead you can use the evaluate function which allows the dynamic evaluation of groovy expressions using this scripts binding as the variable scope. Something like:

city='Petersburg'
varname='city' 
varvalue=evaluate(varname)
println(varvalue)​

You can also use varvalue=evaluate varname as groovy allows to omit the parentheses when running the function with a single parameter.

  • Related