简体   繁体   English

Jenkins Pipeline Jenkinsfile 加载外部常规类

[英]Jenkins Pipeline Jenkinsfile load external groovy class

Could anyone advice on how to load external groovy class into the Jenkinsfile ?任何人都可以就如何将外部 groovy 类加载到 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工具.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.在您的Tools.groovy您必须有一个 return 语句...因为您要在类中调用函数,所以您必须在最后返回 new Demo(),这会将对象的引用返回到 mytools。

In addition to this you can always use groovy class loader.除此之外,您始终可以使用 groovy 类加载器。

if your external groovy file is in the same repository that JenkinsFile resides you can simply use "load" as showen below如果您的外部 groovy 文件位于 JenkinsFile 所在的同一存储库中,您可以简单地使用“加载”,如下所示

mytools = load 'Tools.groovy'

If its in another repo, you need to checkout scm before loading the groovy file as below如果它在另一个仓库中,您需要在加载 groovy 文件之前签出 scm,如下所示

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工具.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)
       }
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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