Search code examples
jenkinsgroovyjenkins-pipelinejenkins-groovy

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


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)
                }
            }
        }
    }

Solution

  • 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