I have a groovy file, I want to run from the Jenkinsfile.
ie. load script.groovy
However, I am not sure how I can reference this file if it is store
There's one scenario that I haven't seen anyone mention. Which is how to load the Groovy scripts when the job is supposed to run on a Jenkins agent/slave, rather than on the master.
Since the master is the one that checks out the Jenkins pipeline project from SCM, the Groovy scripts are only found in the master's file system. So while this will work:
node {
def workspace = pwd()
def Bar = load "${workspace}@script/Bar.groovy"
Bar.doSomething()
}
It's only a happy coincidence because the node that clones the pipeline from SCM is the same one that attempts to load the groovy scripts in it. However, just adding the name of a different agent to execute on:
node("agent1"){
def workspace = pwd()
def Bar = load "${workspace}@script/Bar.groovy"
Bar.doSomething()
}
Will fail, resulting in:
java.io.IOException: java.io.FileNotFoundException: /Jenkins/workspace/Foo_Job@script/Bar.groovy (No such file or directory)
This is because this path:
/Jenkins/workspace/Foo_Job@script/
Only exists on the master Jenkins box. Not in the box running agent1.
So if you're facing this issue, make sure to load the groovy scripts from the master into globally declared variables, so the agent can then use them:
def Bar
node {
def workspace = pwd()
if(isUnix()){
Bar = load "${workspace}@script/Bar.groovy"
}
else{
Bar = load("..\\workspace@script\\Bar.groovy")
}
}
node("agent1"){
Bar.doSomething()
}
Note: The variable used to pass the module between nodes must be declared outside the node blocks.