e.t.
e.t.

Reputation: 115

How to extract sections of Jenkins pipeline script into classes?

I want to refactor my Jenkins pipeline script into classes for readability and reuse.

The problem is i get exceptions when doing so. Let's look at a simple example:

When i run

echo currentBuild.toString()

everything is fine

But when i extract it into a class as so:

class MyClass implements Serializable {
    def runBuild() {
        echo currentBuild.toString()
    }
}
new MyClass().runBuild()

i get an exception:

Started by user admin
Replayed #196
[Pipeline] End of Pipeline
groovy.lang.MissingPropertyException: No such property: currentBuild for class: MyClass

What is the proper way of extracting pipeline code in to classes?

Upvotes: 10

Views: 8913

Answers (2)

lethe3000
lethe3000

Reputation: 153

your code missing declare class field script

class MyClass implements Serializable {

    def script

    MyClass(def script) {
        this.script=script
    }

    def runBuild() {
        script.echo script.currentBuild.toString()
    }
}

this code should be ok @bram

Upvotes: 3

sshepel
sshepel

Reputation: 890

You are on the right way, but the problem is that you didn't pass the script object to the instance of your class and was trying to call method which is not defined in the class that you have created.

Here is one way to solve this:

// Jenkins file or pipeline scripts editor in your job
new MyClass(this).runBuild()

// Class declaration
class MyClass implements Serializable {
    def script
    MyClass(def script) {
        this.script=script
    }
    def runBuild() {
        script.echo script.currentBuild.toString()
    }
}

Upvotes: 13

Related Questions