Jenkins Pipelines:加载外部 Jenkins 管道脚本时重新使用工作区

Jenkins Pipelines: Re-use workspace when loading an external Jenkins pipeline script

我有以下用例:

  1. Checkout/pull 某个 Git 修订版,使用编写的管道脚本
    (我需要这个因为我动态检索修订)

  2. 从该修订版加载 Jenkins 管道文件,该文件位于先前签出的文件中

  3. 此文件将依赖于同一签出修订版中的文件
    (因此,来自 same 工作区)

问题:加载的 Jenkins 管道文件在 new 工作区中执行。但它是空的。我需要该文件在 相同的旧 工作区中执行。

我想,也许是因为包围了 node,因为 node 关键字创建了工作区,如文档中所述。但是当我试图在 外部 node 加载它时,Jenkins 不允许这样做,因为 "leaving the sandbox".

注意:jenkins-pipeline-file 已找到并真正执行。问题是执行期间。


请看示例代码:

内联管道脚本

node('master') {
  def latestBuildableRevision = readFile '/my/LATEST-BUILDABLE-REVISION.txt'

  checkout poll:false,
   scm:[$class:'GitSCM', branches:[[name:latestBuildableRevision]],
   doGenerateSubmoduleConfigurations:false,
   extensions:[[$class: 'CleanBeforeCheckout']], submoduleCfg:[],
    userRemoteConfigs:[[credentialsId:'...', url:'...']]]

  load 'further-script-logic.jenkins'
}

文件:进一步脚本-logic.jenkins

node('master') {
   // make use of certain files
   // assumption: pwd() is the *same* workspace which were checked-out before
   // problem: it's not, it's a new empty workspace
}

一种解决方法是described here

  1. 您必须在 调用程序脚本的末尾使用 {...}() 大括号
  2. 您必须将调用的脚本重写为return闭包(lambda)
    {-> /* former code */ }

这样,您就不会 "give away" 将程序流控制到已执行的脚本。相反,您使用它的 returned 闭包和 "call it yourself"。这会阻止 Jenkins 创建更多的工作空间。

遗憾的是,我不知道这个解决方案是否允许在被调用脚本的调用脚本 and/or 中声明多个节点。

我已将这些更改合并到您的示例代码中。
查找标有 "<--- CHANGE".

的行

内联管道脚本

node('master') {
  def latestBuildableRevision = readFile '/my/LATEST-BUILDABLE-REVISION.txt'

  checkout poll:false,
   scm:[$class:'GitSCM', branches:[[name:latestBuildableRevision]],
   doGenerateSubmoduleConfigurations:false,
   extensions:[[$class: 'CleanBeforeCheckout']], submoduleCfg:[],
    userRemoteConfigs:[[credentialsId:'...', url:'...']]]

  load 'further-script-logic.jenkins'
}()   // <--- CHANGE 1

文件:进一步脚本-logic.jenkins

{->   // <--- CHANGE 2
  node('master') {
    // .....
  }
}