我想将管道常用的函数收集到一个单独的文件中。我创建了目录结构:
vars/
...commonFunctions.groovy
pipeline.jenkinsfile
anotherPipeline.jenkinsfile
commonFunctions.groovy:
def buildDocker(def par, def par2) {
println("build docker...")
}
return this;
在 pipeline.jenkinsfile 中我想调用 buildDocker 函数。我怎样才能做到这一点?我在管道中简单地尝试了
commonFunctions.buildDocker(par1, par2)
,但收到 MethodNotFound 错误。
更新:
pipeline.jenkins文件的相关部分:
stage('Checkout') {
steps {
checkout([$class : 'GitSCM',
branches : [[name: gitCommit]],
userRemoteConfigs: [[credentialsId: gitCredId, url: gitUrl]]
])
}
}
stage("Build Docker") {
steps {
catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
script {
// here want to call function from another file
commonFunctions.buildDocker(par1, par2)
}
}
}
}
首先尝试像这样在 pipeline.jenkinsfile 中加载该文件并像这样使用它。所以你的答案是这样的
load("commonFunctions.groovy").buildDocker(par1, par2)
确保将
return this
添加到您的情况下的 groovy 脚本末尾 commonFunctions.groovy
文件内
您也可以尝试这个插件:Pipeline Remote Loader 您不需要使用
checkout scm
以下是文档中如何使用它的示例:
stage 'Load a file from GitHub'
def helloworld = fileLoader.fromGit('examples/fileLoader/helloworld',
'https://github.com/jenkinsci/workflow-remote-loader-plugin.git', 'master', null, '')
stage 'Run method from the loaded file'
helloworld.printHello()
我想在@Dathrath 的答案中添加一些更多细节。如上所述,它在定义的阶段中工作,但一旦该阶段关闭就会超出范围。
但是!如果您在全局级别定义它 - 在管道启动之前 - 它在管道生命周期的范围内!
示例:
def testScript
pipeline {
agent any
stages {
stage('Test') {
steps {
script {
testScript = load('src/test_src.groovy')
}
}
}
stage('another stage') {
steps {
script {
testScript.test_source('max')
}
}
}
}
}
请注意,线条必须位于
script{}
块内。
将
return this
行添加到脚本中至关重要:
def test_source(String test) {
echo test
}
return this