Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign to env in loop inside Jenkins declarative pipeline script block

I have a problem assigning to the env variable in loop. I basically want to copy everything from user input form to env:

for (elem in userInput)
  env["${elem.key}"] = "${elem.value}"

however this fails with:

org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use staticMethod
org.codehaus.groovy.runtime.DefaultGroovyMethods putAt java.lang.Object java.lang.String java.lang.Object
    at org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.StaticWhitelist.rejectStaticMethod(StaticWhitelist.java:189)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onSetArray(SandboxInterceptor.java:474)
    at org.kohsuke.groovy.sandbox.impl.Checker$11.call(Checker.java:438)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedSetArray(Checker.java:445)
    at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.setArray(SandboxInvoker.java:49)
    at com.cloudbees.groovy.cps.impl.ArrayAccessBlock.rawSet(ArrayAccessBlock.java:26)
    at WorkflowScript.run(WorkflowScript:120)
    at ___cps.transform___(Native Method)
    ...

Assigning this way works:

env.KEY1 = userInput['KEY1']
env.KEY2 = userInput['KEY2']

However I'd still prefer to update the env in a loop to avoid duplication and possibility of typos, is there any way to do that/merge with the input data somehow? (and yes, the pipeline is declarative, running in a sandbox and it should remain as such)

like image 671
EmDroid Avatar asked Sep 15 '25 02:09

EmDroid


1 Answers

Approve putAt method in the sandbox.

Alternatives can be

env.put(elem.key, elem.value)
env."${elem.key}" = elem.value

Also never use double quotes in this syntax env["key"]. Because env["key"] and env['key'] are two different keys. In your example you'd better go with just env[elem.key] or env[elem.key.toString()] if elem.key may not be a string. See Why Map does not work for GString in Groovy?

like image 134
Vitalii Vitrenko Avatar answered Sep 16 '25 21:09

Vitalii Vitrenko