如何从 Jenkins 管道中的另一个文件调用函数?

lle*_*viy 8 groovy jenkins jenkins-groovy jenkins-pipeline

我想将管道常用的函数收集在一个单独的文件中。我创建了目录结构:

vars/
...commonFunctions.groovy
pipeline.jenkinsfile
anotherPipeline.jenkinsfile
Run Code Online (Sandbox Code Playgroud)

commonFunctions.groovy:

def buildDocker(def par, def par2) {
  println("build docker...")
}

return this;
Run Code Online (Sandbox Code Playgroud)

在 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)
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Das*_*kar 10

首先尝试像这样在 pipeline.jenkinsfile 中加载该文件并像这样使用它。所以你的答案是这样的

load("commonFunctions.groovy").buildDocker(par1, par2)
Run Code Online (Sandbox Code Playgroud)

确保添加return this到 groovy 脚本的末尾,该脚本在您的情况下commonFunctions.groovy位于文件内