Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkins Pipeline Jenkinsfile load external groovy class

Could anyone advice on how to load external groovy class into the Jenkinsfile ? In general, I would like to build instance by passing parameters via constructor. Sample code below.

Jenkinsfile

stage('Demo stage') {
   //missing part  
  
}

Tools.groovy

public class Demo {
     String message;
     
     Demo(String message) {
        this.message=message;
     }
     

    public void print(def script) {
        script.sh "echo " + message
    }
}
like image 258
ninja Avatar asked Oct 30 '22 16:10

ninja


2 Answers

It requires a helper function to do so.

Tools.groovy

public class Demo {
    String message;
     
    Demo(String message) {
        this.message = message;
    }

    public void print(def script) {
        script.sh "echo " + message
    }
}

Demo createDemo(String message) {
    new Demo(message)
}

return this

Jenkinsfile

stage('Demo stage') {
   steps {
       script {
           Object lib = load 'path/to/Tools.groovy'
           Object demo = lib.createDemo('a demo')
           demo.print(this)
       }
   }
}
like image 124
ken Avatar answered Nov 15 '22 05:11

ken


mytools = load 'Tools.groovy'
public class Demo {

}
return new Demo() ;

In your Tools.groovy you have to have a return statement... Since you are looking to call functions inside a class , you have to return new Demo() at the end ,this would return reference of the object to mytools.

In addition to this you can always use groovy class loader.

like image 43
user7485194 Avatar answered Nov 15 '22 07:11

user7485194