我正在尝试将内容从Jenkinsfile中分离出来, 以制作一个时髦的脚本。但是它无法调用这些脚本:这是代码:
#!/usr/bin/env groovy node('test-node'){ stage('Checkout') { echo "${BRANCH_NAME} ${env.BRANCH_NAME}" scm Checkout } stage('Build-all-targets-in-parallel'){ def workspace = pwd() echo workspace parallel( 'first-parallel-target' : { // Load the file 'file1.groovy' from the current directory, into a variable called "externalMethod". //callScriptOne() def externalMethod = load("file1.groovy") // Call the method we defined in file1. externalMethod.firstTest() }, 'second-parallel-target' : { //callScriptTwo() def externalMethod = load("file2.groovy") // Call the method we defined in file1. externalMethod.testTwo() } ) } stage('Cleanup workspace'){ deleteDir() } }
file.groovy
#!groovy def firstTest(){ node('test-node'){ stage('build'){ echo "Second stage" } stage('Cleanup workspace'){ deleteDir() } } }
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
如果Jenkinsfile要从外部文件中获取可用的方法,则需要执行以下操作
Jenkinsfile
在您的中file1.groovy,返回对方法的引用
file1.groovy
def firstTest() { // stuff here } def testTwo() { //more stuff here } ... return [ firstTest: this.&firstTest, testTwo: this.&testTwo ]
EDIT
evaluate does not seem to be required
evaluate
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. 请注意,不允许使用 参数替换(进行轻量级签出)
readTrusted
从轻量级结帐:
如果选择此选项,请尝试直接从 SCM 获取管道脚本内容,而不执行完整的检出。这种模式的优点是 效率高。但是,您将不会获得基于 SCM的任何更改日志或轮询。(如果在构建过程中使用checkout scm,则将填充 变更日志并初始化轮询。) 在这种模式下,构建参数也不会替换为SCM配置。仅选定的SCM插件 支持此模式。
至少对我有用