如何“包含”另一个文件作为 Jenkins Pipeline 定义的一部分

Cas*_*ato 15 include jenkins-pipeline

我们有一个大型项目,有多个单独的声明性管道文件定义。这用于从单个代码库构建不同的应用程序和安装程序。

目前,所有这些文件都包含一大块“代码”,用于生成电子邮件正文和 JIRA 更新消息。例子:

// Get a JIRA's to add Comments to
// Return map of JIRA id to comment text from all commits for that JIRA
@NonCPS
def getJiraMap() {
  a bunch of stuff
return jiraset
}

// Get the body text for the emails
def getMailBody1() {
    return "See: ${BUILD_URL}\n\nChanges:\n" + getChangeString() + "\n" + testStatuses()
}

etc...
Run Code Online (Sandbox Code Playgroud)

我想做的是将所有这些常用方法放在一个单独的文件中,所有其他管道文件都可以包含该文件。这看起来应该很简单,但我发现的所有示例似乎都相当复杂,涉及单独的 SCM - 这不是我想要的。

更新:

经过该链接中给出的各种建议,我创建了以下文件 - BuildTools.groovy:请注意,该文件与使用它的 jenkins 管道文件位于同一目录中。

import hudson.tasks.test.AbstractTestResultAction
import hudson.model.Actionable

Class BuildTools {

// Get a JIRA's to add Comments to
// Return map of JIRA id to comment text from all commits for that JIRA
@NonCPS
def getJiraMap() {
    def jiraset = [:]
.. whole bunch of stuff ..
Run Code Online (Sandbox Code Playgroud)

以下是我尝试过的各种事情以及结果。

File sourceFile = new File("./AutomatedBuild/BuildTools.groovy");
Class gcl = new GroovyClassLoader(getClass().getClassLoader()).parseClass(sourceFile);
GroovyObject bt = (GroovyObject) gcl.newInstance();

Fails with:
    org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use method java.lang.Class getClassLoader
Run Code Online (Sandbox Code Playgroud)
evaluate(new File("./AutomatedBuild/BuildTools.groovy"))
def bt = new BuildTools()

Fails with:
    15:29:07  WorkflowScript: 8: unable to resolve class BuildTools 
    15:29:07   @ line 8, column 10.
    15:29:07     def bt = new BuildTools()
    15:29:07              ^
Run Code Online (Sandbox Code Playgroud)
import BuildTools
def bt = new BuildTools()

Fails with:
    15:35:58  WorkflowScript: 16: unable to resolve class BuildTools (note that BuildTools.groovy is in the same folder as this script)
    15:35:58   @ line 16, column 1.
    15:35:58     import BuildTools
    15:35:58     ^
Run Code Online (Sandbox Code Playgroud)
GroovyShell shell = new GroovyShell()
def bt = shell.parse(new File("./AutomatedBuild/BuildTools.groovy"))

Fails with:
    org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use new groovy.lang.GroovyShell
Run Code Online (Sandbox Code Playgroud)

小智 0

专为您设计的共享库。

您还可以使用加载步骤从 groovy 文件添加类或函数来加载您的类函数和阶段:

my_module = load 'path/to/file/in/repo.groovy'
my_module.myCoolClass()
Run Code Online (Sandbox Code Playgroud)