如何将其他 groovy 文件导入到我的 pipeline.groovy 文件中?

TS_*_*Dev 5 groovy jenkins jenkins-pipeline

我对 Groovy 完全是菜鸟。对于上下文,我有一个使用 deploy.pipeline.groovy 脚本的 Jenkins 管道。我还有一个用于 git PR 的 test.pipeline.groovy 脚本。

我试图减少两个脚本中的重复代码,因此我创建了一个 Globals.groovy 脚本来存储常量,并创建了一个 Functions.groovy 脚本来存储两个管道脚本的可重用函数。所有文件都位于同一目录中,但我不知道如何将全局和函数脚本导入到管道脚本中以供使用。

我的 Globals.groovy 文件是这样的:

import groovy.transform.Field
@CompileStatic class Globals {
   @Field final String test1 = 'first test'
   @Field final String test2 = 'second test'
}
Run Code Online (Sandbox Code Playgroud)

我的 Functions.groovy 文件是这样的:

@CompileStatic class Functions {
   def TestMessage1() { println globals.test1 }
   def TestMessage2() { println globals.test2 }
}
Run Code Online (Sandbox Code Playgroud)

两个管道脚本都有一个“测试”阶段,如下所示:

def runTests{
   stage('Test') {
      functions.TestMessage1()
      functions.TestMessage1()
   }
}
Run Code Online (Sandbox Code Playgroud)

我不知道如何将 Globals.groovy 脚本导入或加载到 Functions.groovy 脚本中,然后将 Functions.groovy 脚本导入或加载到我的脚本中。

我尝试将其放在 Functions.groovy 脚本的顶部:

def globals = load('Globals.groovy')
Run Code Online (Sandbox Code Playgroud)

这是我的管道脚本的顶部

def functions = load('Functions.groovy')
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Kau*_*s2b 3

您可以只在常规文件中包含函数,并且需要在底部返回

这是我的詹金斯文件:

def pipeline
node('master') {
    checkout scm
    pipeline = load 'script.groovy'
    pipeline.execute()
}
Run Code Online (Sandbox Code Playgroud)

这是我的 script.groovy (与仓库中的 Jenkinsfile 级别相同)

//import ...

def execute() {
    println 'Test'
}

return this
Run Code Online (Sandbox Code Playgroud)

詹金斯作业输出:

[Pipeline] load
[Pipeline] { (script.groovy)
[Pipeline] }
[Pipeline] // load
[Pipeline] echo
Test
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
Run Code Online (Sandbox Code Playgroud)