Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I import a Groovy class into a Jenkinfile?

How do I import a Groovy class within a Jenkinsfile? I've tried several approaches but none have worked.

This is the class I want to import:

Thing.groovy

class Thing {
    void doStuff() { ... }
}

These are things that don't work:

Jenkinsfile-1

node {
    load "./Thing.groovy"

    def thing = new Thing()
}

Jenkinsfile-2

import Thing

node {
    def thing = new Thing()
}

Jenkinsfile-3

node {
    evaluate(new File("./Thing.groovy"))

    def thing = new Thing()
}
like image 411
Leonhardt Koepsell Avatar asked Aug 29 '16 14:08

Leonhardt Koepsell


People also ask

How do I load Groovy in Jenkins pipeline?

In Jenkinsfile, simply use load step to load the Groovy script. After the Groovy script is loaded, the functions insides can be used where it can be referenced, as shown above.

Does Jenkinsfile use Groovy?

The Jenkinsfile is written using the Groovy Domain-Specific Language and can be generated using a text editor or the Jenkins instance configuration tab. The Declarative Pipelines is a relatively new feature that supports the concept of code pipeline. It enables the reading and writing of the pipeline code.


1 Answers

You can return a new instance of the class via the load command and use the object to call "doStuff"

So, you would have this in "Thing.groovy"

class Thing {
   def doStuff() { return "HI" }
}

return new Thing();

And you would have this in your dsl script:

node {
   def thing = load 'Thing.groovy'
   echo thing.doStuff()
}

Which should print "HI" to the console output.

Would this satisfy your requirements?

like image 187
Daniel Omoto Avatar answered Oct 13 '22 18:10

Daniel Omoto