简体   繁体   中英

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
    }
}
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.

if your external groovy file is in the same repository that JenkinsFile resides you can simply use "load" as showen below

mytools = load 'Tools.groovy'

If its in another repo, you need to checkout scm before loading the groovy file as below

checkout changelog: false, poll: false, scm: [$class: 'GitSCM', branches: [[name: '*/master']], doGenerateSubmoduleConfigurations: false, extensions: [[$class: 'RelativeTargetDirectory', relativeTargetDir: 'jenkins-scripts']], submoduleCfg: [], userRemoteConfigs: [[credentialsId: '******', url: 'https://github.com/jenkins_scripts.git']]]

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)
       }
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM