Using the groovy class in other jenkins groovy scripts

I have 4 groovy scripts (2 - 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 do not see problems running scripts locally.

But on jenkins, even if I provide JobConfig.class in the same place where these scripts are, I cannot get it to work. I read here that I do not need to compile while JobConfig.groovy is in CLASSPATH. How do I do this with jenkins? Or is there another solution?

+6
source share
2 answers

If you do not want to compile the groovy class (s) and then add the compiled classes to the class path, you can use the classes in groovy scripts like this:

Considering the groovy class

 class GroovyClass { def GroovyClass(someParameter) {} def aMethod() {} } 

you can use the class in a 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() 
+2
source

I would do the following: instead of making everything work manually, I would create a maven or gradle one project and organize your groovy files in the given project. When configure maven or gradle to start it. When maven or gradle starts it without any problems, you can give it jenkins.

Jenkins will probably find maven projects, and for gradle you will need to check, however, one thing is for sure, maven runs the groovy project locally, it will work without any problems under Jenkins.

Please try let me know.

0
source

Source: https://habr.com/ru/post/950055/


All Articles