如何将其他 groovy 文件导入到我的 pipeline.groovy 文件中?
How can I import other groovy files into my pipeline.groovy files?
我完全是 Groovy 的菜鸟。对于上下文,我有一个使用 deploy.pipeline.groovy 脚本的 Jenkins 管道。我还有一个 test.pipeline.groovy 用于 git PR 的脚本。
我试图减少两个脚本中的重复代码,因此我创建了一个 Globals.groovy 脚本来存储我的常量和一个 Functions.groovy 脚本来存储两个管道脚本的可重用函数。所有文件都在同一目录中,但我不知道如何将我的 Globals 和 Functions 脚本导入到管道脚本中以供使用。
我的Globals.groovy文件是这样的:
import groovy.transform.Field
@CompileStatic class Globals {
@Field final String test1 = 'first test'
@Field final String test2 = 'second test'
}
我的Functions.groovy文件是这样的:
@CompileStatic class Functions {
def TestMessage1() { println globals.test1 }
def TestMessage2() { println globals.test2 }
}
两个管道脚本都有一个“测试”阶段,如下所示:
def runTests{
stage('Test') {
functions.TestMessage1()
functions.TestMessage1()
}
}
我不知道如何将我的 Globals.groovy 脚本导入或加载到我的 Functions.groovy 脚本中,然后将我的 Functions.groovy 脚本导入或加载到我的脚本中。
我试过将它放在我的 Functions.groovy 脚本的顶部:
def globals = load('Globals.groovy')
这是我的管道脚本的顶部
def functions = load('Functions.groovy')
我做错了什么?
您可以只在 groovy 文件中包含函数,并且底部需要一个 return
这是我的 Jenkins 文件:
def pipeline
node('master') {
checkout scm
pipeline = load 'script.groovy'
pipeline.execute()
}
这是我的script.groovy(与回购中的 Jenkinsfile 相同级别)
//import ...
def execute() {
println 'Test'
}
return this
Jenkins 作业输出:
[Pipeline] load
[Pipeline] { (script.groovy)
[Pipeline] }
[Pipeline] // load
[Pipeline] echo
Test
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
我完全是 Groovy 的菜鸟。对于上下文,我有一个使用 deploy.pipeline.groovy 脚本的 Jenkins 管道。我还有一个 test.pipeline.groovy 用于 git PR 的脚本。
我试图减少两个脚本中的重复代码,因此我创建了一个 Globals.groovy 脚本来存储我的常量和一个 Functions.groovy 脚本来存储两个管道脚本的可重用函数。所有文件都在同一目录中,但我不知道如何将我的 Globals 和 Functions 脚本导入到管道脚本中以供使用。
我的Globals.groovy文件是这样的:
import groovy.transform.Field
@CompileStatic class Globals {
@Field final String test1 = 'first test'
@Field final String test2 = 'second test'
}
我的Functions.groovy文件是这样的:
@CompileStatic class Functions {
def TestMessage1() { println globals.test1 }
def TestMessage2() { println globals.test2 }
}
两个管道脚本都有一个“测试”阶段,如下所示:
def runTests{
stage('Test') {
functions.TestMessage1()
functions.TestMessage1()
}
}
我不知道如何将我的 Globals.groovy 脚本导入或加载到我的 Functions.groovy 脚本中,然后将我的 Functions.groovy 脚本导入或加载到我的脚本中。
我试过将它放在我的 Functions.groovy 脚本的顶部:
def globals = load('Globals.groovy')
这是我的管道脚本的顶部
def functions = load('Functions.groovy')
我做错了什么?
您可以只在 groovy 文件中包含函数,并且底部需要一个 return
这是我的 Jenkins 文件:
def pipeline
node('master') {
checkout scm
pipeline = load 'script.groovy'
pipeline.execute()
}
这是我的script.groovy(与回购中的 Jenkinsfile 相同级别)
//import ...
def execute() {
println 'Test'
}
return this
Jenkins 作业输出:
[Pipeline] load
[Pipeline] { (script.groovy)
[Pipeline] }
[Pipeline] // load
[Pipeline] echo
Test
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS