Jenkins声明式管道:在阶段外运行脚本{}块

时间:2020-03-27 04:48:15

标签: jenkins groovy jenkins-pipeline jenkins-groovy

目标:

我需要运行类似于此的代码片段,以便从另一个詹金斯工作中获取一些信息:

 script {
    def buildJobName = Jenkins.instance.getItemByFullName('Jobs/myOtherJob')
    def buildJobId = buildJobName.getLastSuccessfulBuild()
 }

文档清楚地说明了如何在声明性管道中运行脚本: https://jenkins.io/doc/book/pipeline/syntax/#script,但它明确地在阶段中运行它们。

此问题范围专门与如何在管道阶段之外运行“任何”脚本块有关,因此并不确定我的脚本在做什么。可以应用于声明性管道中的任何常规脚本。


我的用例将在一个步骤范围之外全局地使用此数据

通常,对于整个管道中的“全局”事物,我使用 environment{}块来声明变量。但是,我似乎无法使脚本在以下位置正确执行environment{}块,至少经过我的尝试。

所以我的问题是:

如何在声明性管道中运行脚本部分,定义以后可在整个管道中使用的变量?

1 个答案:

答案 0 :(得分:1)

经过更多研究后发现了这一点。

也许有一种更好的方法,但是我可以通过将脚本放入函数中并将env var值设置为函数的返回值来使此工作正常进行:

def get_last_build() {
  def buildJobName = Jenkins.instance.getItemByFullName('Jobs/myOtherJob')
  def lastBuildId = buildJobName.getLastSuccessfulBuild()
  echo 'Using Build ID: ' + lastBuildId
  return lastBuildId
}

pipeline {
  agent any
  environment {
    MY_GLOBAL_VAR = get_last_build()
  }
  // other stuff
}