3

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)

EmDroid
  • 5,918
  • 18
  • 18
  • Probably failing because your script is running in a sandbox. Can you clear the execute in sandbox checkbox? – ernest_k Mar 16 '18 at 17:33
  • 2
    Or can you side-step it with `env."${elem.key}" = elem.value`? – tim_yates Mar 16 '18 at 17:45
  • Yeah, that works, thanks! Even with `env."${elem.key}" = elem.value`. I'm still pretty new in groovy, didn't know that such syntax is possible :) – EmDroid Mar 16 '18 at 17:51

1 Answers1

6

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?

Vitalii Vitrenko
  • 9,763
  • 4
  • 43
  • 62