jenkins - 如何从 Jenkins 文件调用 groovy 脚本?

标签 jenkins groovy

我正在尝试将 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()
  }
}

文件.groovy

#!groovy

def firstTest(){

  node('test-node'){
    
    stage('build'){
      echo "Second stage"
    }
    
    stage('Cleanup workspace'){
      deleteDir()
    }
  }
}

看起来 Jenkinsfile 能够调用 file1.groovy 但总是给我一个错误:

java.lang.NullPointerException: Cannot invoke method firstTest() on null object

最佳答案

看起来您在正在加载的脚本中错过了返回:

return this

请在此处检查: https://jenkins.io/doc/pipeline/steps/workflow-cps/#load-evaluate-a-groovy-source-file-into-the-pipeline-script

因此,您调用的加载文件将具有如下结构:

def exampleMethod() {
    //do something
}

def otherExampleMethod() {
    //do something else
}
return this

这样你就不应该得到空对象

关于jenkins - 如何从 Jenkins 文件调用 groovy 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43324268/

相关文章:

eclipse - 在 Eclipse JUnit View 中显示 Jenkins 测试结果

java - 无法使用线程执行代码块中的所有语句

xml - Grails/Groovy - 将对象呈现/直接转换为 XML 以保存到文件

jenkins - 我如何将 Jenkinsfile 支持添加到 Visual Studio 2017

grails - Geb 登录规范示例

continuous-integration - playframework 自动测试 Jenkins CI 等待完成?

jenkins - 组合多个jenkins共享库

continuous-integration - 使用 Jenkins/jetty 自动部署

shell - 在多行中分隔 sh 命令

Jenkins 转义 sed 命令