How can I call function from another file in Jenkins pipeline?

Viewed 3905

I want to collect functions common for pipelines in a separate file. I created directories' structure:

vars/
...commonFunctions.groovy
pipeline.jenkinsfile
anotherPipeline.jenkinsfile

commonFunctions.groovy:

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

return this;

In pipeline.jenkinsfile I want to call buildDocker function. How can I do this? I tried simply commonFunctions.buildDocker(par1, par2) in the pipelines, but get MethodNotFound error.

UPD:

relevant part of 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)
                }
            }
        }
    }
2 Answers

First try to load that file in pipeline.jenkinsfile like this and use it like this. So your answer would be this

load("commonFunctions.groovy").buildDocker(par1, par2)

Make sure you add return this to the end of groovy script which is in your case commonFunctions.groovy inside file

You can try also this plugin: Pipeline Remote Loader You do not need to use checkout scm

Here is an example from the documentation how to use it:

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()
Related