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?
To create a simple pipeline from the Jenkins interface, perform the following steps: Click New Item on your Jenkins home page, enter a name for your (pipeline) job, select Pipeline, and click OK. In the Script text area of the configuration screen, enter your pipeline syntax.
As mentioned above, unlike Jenkinsfile s you define through Blue Ocean (above) or in source control (below), Jenkinsfile s entered into the Script text area area of Pipeline projects are stored by Jenkins itself, within the Jenkins home directory.
First, try the same operation in stages and step, as in here: pipeline { agent any stages { stage ('push artifact') { steps { sh 'mkdir archive' sh 'echo test > archive/test. txt' zip zipFile: 'test. zip', archive: false, dir: 'archive' archiveArtifacts artifacts: 'test.
Orphaned Item Strategy Computed folders can remove items immediately or leave them based on a desired retention strategy. By default, items will be removed as soon as the folder computation determines they are no longer present.
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()
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With