Jenkins并行管道触发相同的构建

shstlldc  于 2023-10-17  发布在  Jenkins
关注(0)|答案(3)|浏览(157)

**问题:**Jenkins管道仅触发上游作业的单个作业

我在数组中有一个jenkins作业列表,我试图从它构建构建作业的对象并并行运行它们。
例如

def testJobs = [
  'pipeline1',
  'pipeline2'
]
def buildList = [:]

for (jobName in testJobs){
  buildList[jobName] = {
    build job: jobName,  propagate: false
  }
}

def buildResults = parallel (buildList)

对于上面的片段,我只能看到所有管道的单个构建,如下所示。(它总是指向列表中的最后一个管道.例如pipeline2

[pipeline1] Starting building: pipeline2 #5

[pipeline2] Starting building: pipeline2 #5

我也尝试过使用虚拟参数来使每个构建的不同(即使它已经有了不同的作业名称),但这不起作用。
build job: jobName, parameters: [string(name: "Dummy", value: "${jobName}")], propagate: false
但是,如果我手动创建对象,而不是for循环,那么它就可以完美地工作(如下所示)。
例如

def buildList = [:]

buildList[pipeline1] = {
  build job: pipeline1,  propagate: false
}

buildList[pipeline2] = {
  build job: pipeline2,  propagate: false
}

def buildResults = parallel (buildList)

输出量:

[pipeline1] Starting building: pipeline1 #3

[pipeline2] Starting building: pipeline2 #6

对于大量的管线,手动调整管线的长度是不可行的。有人有同样的问题吗?或者fora循环的第一步方法有什么问题?

ht4b089n

ht4b089n1#

这个问题与闭包如何在for循环中工作有关。
for只示例化一个在每次迭代中被重新分配的变量,在你的例子中是jobName变量,因此当循环结束时,for中创建的所有闭包的jobName都有相同的值,这个值是最后分配给它的值。
Groovy closures为每次迭代创建一个新变量,所以如果将for更改为each,它将按预期工作:

def testJobs = [
  'pipeline1',
  'pipeline2'
]
def buildList = [:]

// use each instead of for
testJobs.each{ jobName -> 
  buildList[jobName] = {
    build job: jobName,  propagate: false
  }
}

def buildResults = parallel (buildList)
bprjcwpo

bprjcwpo2#

这确实与关闭有关。
这可能会更好地工作:

for (jobName in testJobs) {
  def jobNameCopy = jobName
  buildList[jobNameCopy] = {
    build job: jobNameCopy,  propagate: false
  }
}

def buildResults = parallel (buildList)
35g0bw71

35g0bw713#

@albciff是绝对正确的,但是如果我们要使用函数式风格,让我们一路走下去:)

def testJobs = [
  'pipeline1',
  'pipeline2',
]

def buildList = testJobs.collectEntries { jobName -> [
  jobName,
  {
    build job: jobName, propagate: false
  }
]}

def buildResults = parallel(buildList)

相关问题