Jenkins variable in groovy script

2019-07-26 07:19发布

问题:

I'd like to use "$WORSKPACE" variable into a groovy file called by jenkins script. But all solutions found on SO failed :

// KO : Wks = build.getEnvironment(listener).get('WORKSPACE')
// KO : Wks = "${WORKSPACE}"
/* KO :
def thr = Thread.currentThread()
def build = thr?.executable
def envVarsMap = build.parent.builds[0].properties.get("WORKSPACE")
*/

// KO : def build = this.getProperty('binding').getVariable('build')
// KO : Wks = "%WORKSPACE%"

Message I got : Scripts not permitted to use method groovy.lang.GroovyObject setProperty java.lang.String java.lang.Object (JenkinsHelper.name). Administrators can decide whether to approve or reject this signature.

Any idea of code or option to set to allow Jenkins script to work ?

My sample case :

File JenkinsHelper.groovy :

    class JenkinsHelper {
     def init(String sln) { 
      Wks = "%WORKSPACE%"
     }
    }
return new JenkinsHelper();

Call from jenkins script :

def helper = load 'C:/.../test.groovy'
helper.init("Mon SLN")

Thanks :)

回答1:

This is caused by Jenkins In-process Script Approval as a protection of possible execution of malicious scripts.

If you're an admin, register your pipeline codes in Manage Jenkins > Configure System > Global Pipeline Libraries to avoid this scenario.

References:

  1. https://jenkins.io/doc/book/pipeline/shared-libraries/#global-shared-libraries - Goes in details on writing a library.
  2. https://jenkins.io/doc/book/managing/script-approval


回答2:

You should use groovy-style environenment variable format, not a Windows-style format:

class JenkinsHelper {
 def init(String sln) { 
  Wks = "${WORSKPACE}"
 }
}