首页 > 解决方案 > 詹金斯管道中动态生成的并行块

问题描述

我使用 Jenkins 管道使用“并行”构造同时执行一些构建/部署任务:

stage('tasks')
  parallel('task1': {someFunction(arg=1)}, 
           'task2': {someFunction(arg=2)},
           'task3': {someFunction(arg=3)}
  )
}

有时我想在运行时动态构建这个结构。可能吗 ?

示例:要从 10 个列表中为选定目标复制的文件。

当用户选择 4 个项目时,我想创建一个包含 4 个项目的“并行”结构,然后执行它。

标签: jenkinsjenkins-pipelinejenkins-groovy

解决方案


基本上,您可以创建一个函数,该函数返回保存项目任务的 groovy 闭包映射。

请记住,您需要关闭 groovy 沙盒才能运行它。

#!/usr/bin/env groovy

def getSomeFunction = { arg ->
    // returns the closure with your task, function, run with the chosen parameter
    return {
        println(arg)
    }
}

def getParalellBlock = { number ->
    def  myList =  ['a', 'b', 'c', 'd'] // your list of items
    def blockMap = [:]
    1.upto(number, {
        // Make sure to handle 'index out of range' kind of problems
        blockMap.put(it.toString(), getSomeFunction(myList[it-1]))
    })
    return blockMap
}

node() {
    stage('tasks') {
        // you can supply the parameter from job parameters
        parallel(getParalellBlock(3))
    }
}

推荐阅读