How to extract sections of Jenkins pipeline script into classes?

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

The problem is that I get exceptions when doing this. Consider a simple example:

When i run

echo currentBuild.toString() 

everything is good

But when I fetch it into the class as follows:

 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 correct way to extract code in classes?

+7
jenkins refactoring groovy jenkins-pipeline jenkinsfile
source share
2 answers

You are on the right track, but the problem is that you did not pass the script object to an instance of your class and tried to call a method that is not defined in the class you created.

Here is one way to solve this problem:

 // 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() } } 
+7
source share

your code is missing declare a script class field

 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

+2
source share

All Articles