如何从 Jenkins 管道中的另一个文件调用函数?
How can I call function from another file in Jenkins pipeline?
我想将流水线常用的函数收集到一个单独的文件中。我创建了目录结构:
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.jenkinsfile的相关部分:
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()
我想将流水线常用的函数收集到一个单独的文件中。我创建了目录结构:
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.jenkinsfile的相关部分:
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()