gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 13:53:05 26 4
gpt4 key购买 nike

我正在尝试将 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com