Idan Adar
Idan Adar

Reputation: 44526

How to call a groovy function from a Jenkinsfile?

Despite following this answer and others, I am unable to successfully use a local groovy file in my Jenkinsfile (both are in the same repository).

def deployer = null
...
...
...
pipeline {
   agent {
      label 'cf_slave'
   }

   options {
      skipDefaultCheckout()
      disableConcurrentBuilds()
   }

   stages {
      stage ("Checkout SCM") {
         steps {
            checkout scm
         }
      }
      ...
      ...
      ...
      stage ("Publish CF app") {
          steps {
              script {
                  STAGE_NAME = "Publish CF app"
                  deployer = fileLoader.load ('deployer')

                  withCredentials(...) {   
                      if (BRANCH_NAME == "develop") {
                          ...
                          ...
                          ...
                      } else {
                          deployer.generateManifest()
                      }
                  }
              }
          }
      }
      ...
      ...
  }

deployer.groovy:

#!/usr/bin/env groovy

def generateManifest() {
   sh "..."
   echo "..."
}

In the console log (stack):

[Pipeline] stage
[Pipeline] { (Publish CF app)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
before loading groovy file
[Pipeline] echo
Loading from deployer.groovy
[Pipeline] load
[Pipeline] // load
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage

Update:

It seems the problem was not with loading the file but rather with the contents of the file, where I execute the following which apparently does not play well:

sh "node $(pwd)/config/mustacher manifest.template.yml config/environments/common.json config/environments/someFile.json"
echo "..."

When only the echo is there, this is the stack.

So not the sh "node ..." nor the echo work. Even changing it just to sh "pwd" fails as well. What could it be? the syntax in the file? the way it is called in the pipeline?

If I will make the same node call in the pipeline (for example in the withCredentials if statement, it works.

Upvotes: 8

Views: 24748

Answers (1)

mkobit
mkobit

Reputation: 47319

Add a return this to the bottom of the deployer.groovy file, and then change you load step to use relative path and extension to groovy file like load('deployer.groovy').

The return this is documented on jenkins.io:

Takes a filename in the workspace and runs it as Groovy source text. The loaded file can contain statements at top level or just load and run a closure. For example:

def pipeline
node('slave') {
    pipeline = load 'pipeline.groovy'
    pipeline.functionA()
}
pipeline.functionB()

pipeline.groovy

def pipelineMethod() {
  ...code
}
    
return this

Where pipeline.groovy defines functionA and functionB functions (among others) before ending with return this

Upvotes: 4

Related Questions