I am trying to separate out the contents from a Jenkinsfile into a groovy script to make. But it fails to call these scripts: Here is the code:
file.groovy
Looks like the Jenkinsfile is able to call file1.groovy but always gives me an error:
java.lang.NullPointerException: Cannot invoke method firstTest() on null object
If you want to have methods available in your Jenkinsfile
from an external file you need to do the following
In your file1.groovy
, return references to the methods
def firstTest() { // stuff here } def testTwo() { //more stuff here } ... return [ firstTest: this.&firstTest, testTwo: this.&testTwo ]
EDIT
evaluate
does not seem to be required
def externalMethod = evaluate readFile("file1.groovy")
or
def externalMethod = evaluate readTrusted("file1.groovy")
And as mentioned by @Olia
def externalMethod = load("file1.groovy")
should work
Here is a reference on readTrusted
. Note that no parameter substitution is allowed (does a lightweight checkout)
From lightweight checkout:
If selected, try to obtain the Pipeline script contents directly from the SCM without performing a full checkout. The advantage of this mode is its efficiency; however, you will not get any changelogs or polling based on the SCM. (If you use checkout scm during the build, this will populate the changelog and initialize polling.) Also build parameters will not be substituted into SCM configuration in this mode. Only selected SCM plugins support this mode.
At least that works for me
It looks like you missed return within the scripts you are loading:
return this
Please, check it here: https://jenkins.io/doc/pipeline/steps/workflow-cps/#load-evaluate-a-groovy-source-file-into-the-pipeline-script
So, your called loaded file will have a structure like:
def exampleMethod() { //do something } def otherExampleMethod() { //do something else } return this
This way you shouldn't get null object