How can I call a groovy script from a Jenkins file?

匿名 (未验证) 提交于 2019-12-03 08:50:26

问题:

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

回答1:

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



回答2:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!