Home > Mobile >  How can I import other groovy files into my pipeline.groovy files?
How can I import other groovy files into my pipeline.groovy files?

Time:10-29

I'm a total noob with Groovy. For context I have a Jenkins pipeline that uses a deploy.pipeline.groovy script. I also have a test.pipeline.groovy script for git PRs.

I'm trying to reduce duplicated code in both scripts so I created a Globals.groovy script to store my constants and a Functions.groovy script to store reusable functions for both pipeline scripts. All of the files are in the same directory, but I can't figure out how to import my Globals and Functions scripts into the pipeline scripts for use.

My Globals.groovy file is like this:

import groovy.transform.Field
@CompileStatic class Globals {
   @Field final String test1 = 'first test'
   @Field final String test2 = 'second test'
}

My Functions.groovy file is like this:

@CompileStatic class Functions {
   def TestMessage1() { println globals.test1 }
   def TestMessage2() { println globals.test2 }
}

Both pipeline scripts have a "Test" stage like so:

def runTests{
   stage('Test') {
      functions.TestMessage1()
      functions.TestMessage1()
   }
}

I can't figure out how to import or load my Globals.groovy script into my Functions.groovy script and then my Functions.groovy script into my scripts.

I've tried putting this at the top of my Functions.groovy scripts:

def globals = load('Globals.groovy')

And this at the top of my pipeline scripts

def functions = load('Functions.groovy')

What am I doing wrong?

CodePudding user response:

You can just have functions in your groovy files and need a return at the bottom

Here is my Jenkinsfile:

def pipeline
node('master') {
    checkout scm
    pipeline = load 'script.groovy'
    pipeline.execute()
}

This is my script.groovy (same level as Jenkinsfile in repo)

//import ...

def execute() {
    println 'Test'
}

return this

Jenkins job Output:

[Pipeline] load
[Pipeline] { (script.groovy)
[Pipeline] }
[Pipeline] // load
[Pipeline] echo
Test
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
  • Related