简体   繁体   中英

Using a groovy class in other jenkins groovy scripts

I have 4 groovy scripts (2 are dsl.groovy scripts):

JobConfig.groovy :

class JobConfig {
    final name

    JobConfig(map) {
        name = map['name']
    }
}

topLevel.groovy :

import JobConfig.*

def doSmthWithJobConfig(final JobConfig config) {
    println(config.name);
}

sublevel1.dsl.groovy :

GroovyShell shell = new GroovyShell()
def topLevelScript = shell.parse(new File("topLevel.groovy"))

def jobConfigs = [
    new JobConfig(name: 'JenkinsTestDSLs'),
    new JobConfig(name: 'JenkinsTestDSLs2')
]

jobConfigs.each {
    topLevelScript.doSmthWithJobConfig(it);
}

sublevel2.dsl.groovy :

GroovyShell shell = new GroovyShell()
def topLevelScript = shell.parse(new File("topLevel.groovy"))

def jobConfigs = [
    new JobConfig(name: 'JenkinsTestDSLs3'),
    new JobConfig(name: 'JenkinsTestDSLs4')
]

jobConfigs.each {
    topLevelScript.doSmthWithJobConfig(it);
}

Now if locally I do:

groovyc JobConfig.groovy

,I get no issues with running the scripts locally.

But on jenkins even if I provide the JobConfig.class at the same place where these scripts are, I can't get it running. I read here that I don't need to do any compiling as long as JobConfig.groovy is on the CLASSPATH. How do I do that with jenkins? Or is there another solution?

If you don't want to compile the groovy class(es) and then add the compiled classes to the classpath, you can make use of classes within groovy scripts like this:

Given a groovy class

class GroovyClass {
    def GroovyClass(someParameter) {}

    def aMethod() {}
}

you can use the class in groovy script like this

import hudson.model.*
import java.io.File;
import jenkins.model.Jenkins;

def jenkinsRootDir = build.getEnvVars()["JENKINS_HOME"];
def parent = getClass().getClassLoader()
def loader = new GroovyClassLoader(parent)

def someParameterValue = "abc"

def groovyClass = loader.parseClass(new File(jenkinsRootDir + "/userContent/GroovyScripts/GroovyClass.groovy")).newInstance(someParameterValue)

groovyClass.aMethod()

What I would do is following, instead of trying to make it all work manually, I would create maven project or gradle one and organize your groovy files within resulted project. When configure maven or gradle to run it. Once maven or gradle runs it without any issues, you can give it to jenkins.

Jenkins takes maven projects for sure and for gradle you will have to check, however one thing for sure, is maven runs you groovy project locally it will run without any issues under Jenkins as well.

Please try, let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM