lleviy
lleviy

Reputation: 436

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

Upvotes: 8

Views: 12749

Answers (3)

Max Cascone
Max Cascone

Reputation: 833

I want to add to @Dathrath's answer with some more detail. As commented above, it works in the stage it's defined in, but goes out of scope as soon as that stage closes.

But! If you define it at the global level - before the pipeline starts - it is in scope through the pipe's life!

example:

// Jenkinsfile

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'). // <-- outputs 'max' to the console
        }
      }
    }
  }
}

Note that the lines have to be inside script{} blocks.

And it's critical to add the return this line to the end of the script file - it won't work without it.

// src/test_src.groovy

def test_source(String test) {
  echo test
}

return this

You only need one return this line at the end of the file, regardless of how many functions you define in it. (It's returning the script object to the pipeline scope.)

Additionally! In the same way it's described in the book (and maybe the jenkins docs?) to define a call() function as the "default" function for a script, if you define call() in this script file, you don't have to call a member function to use it. Just the name of the script:

// src/test_src.groovy
def call() {
  echo 'this is a call'
}
return this


// lets you call it this way in the Jenkinsfile:
steps {
  script {
    testScript() // <-- outputs 'this is a call' to the console
  }
}

Upvotes: 2

Dashrath Mundkar
Dashrath Mundkar

Reputation: 9174

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

Upvotes: 10

Catalin
Catalin

Reputation: 484

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

Upvotes: 1

Related Questions