How do you load a groovy file and execute it
If your Jenkinsfile
and groovy file in one repository and Jenkinsfile
is loaded from SCM you have to do:
Example.Groovy
def exampleMethod() { //do something}def otherExampleMethod() { //do something else}return this
JenkinsFile
node { def rootDir = pwd() def exampleModule = load "${rootDir}@script/Example.Groovy " exampleModule.exampleMethod() exampleModule.otherExampleMethod()}
You have to do checkout scm
(or some other way of checkouting code from SCM) before doing load
.
If you have pipeline which loads more than one groovy file and those groovy files also share things among themselves:
JenkinsFile.groovy
def modules = [:]pipeline { agent any stages { stage('test') { steps { script{ modules.first = load "first.groovy" modules.second = load "second.groovy" modules.second.init(modules.first) modules.first.test1() modules.second.test2() } } } }}
first.groovy
def test1(){ //add code for this method}def test2(){ //add code for this method}return this
second.groovy
import groovy.transform.Field@Field private First = nulldef init(first) { First = first}def test1(){ //add code for this method}def test2(){ First.test2()}return this