我如何 运行 在 Jenkins 管道中并行执行 for 循环的每次迭代?

How can I run each iteration of a for loop parallel in Jenkins pipeline?

我有一个管道作业,其中 运行 一些操作序列(例如;构建 >> 运行 >> 报告)。我已经将这个序列放在一个 for 循环中,因为我可以获得一个参数,我应该重复相同的序列多少次。请找到我写的示例代码。

for (int i = 0; i < <param_val>; ++i){
    node{
        stage('Build') {
            build 'Build'
        }
        stage('Run') {
           build 'Run'
        }
        stage('Reporting') {
           build 'Reporting'
        }
    }
}

现在我的代码正在等待一个完整的序列发生,然后继续 运行 下一个序列。那很费时间。我有更多的从属代理,可以 运行 并行处理序列。如何 运行 for 循环的每次迭代并行?

我想到了解决办法: 有一个具有实际序列的管道

node{
        stage('Build') {
            build 'Build'
        }
        stage('Run') {
           build 'Run'
        }
        stage('Reporting') {
           build 'Reporting'
        }
    }

有另一个带有 for 循环的管道,它将触发带有等待的第一个管道:false:

for (int i = 0; i < <param_val>; ++i){
    build(job: 'pipeline-1', wait: false)
}

这个有用吗?或者我们是否有更好的选择来对单个管道执行相同的操作?

将代码放入闭包中的循环中:

def oneNode = { c ->
    node {
        build job: 'Build', parameters: [string(name: 'Component', value: c)]
        build 'Run'
        build 'Reporting'
    }
}

然后制作一个包含所有你想同时 运行 的闭包的地图:

def jobs = [:]
def components = params.Componets.split(",")
for (int i = 0; i < components.size(); ++i) {
    def component = components[i].trim()
    jobs[component] = {
        oneNode(component)
    }
}

最后对生成的地图使用 parallel 步骤:

stage('Build, run, report') {
    <the code from the above steps>
    parallel jobs
}

这对我有用。

def jobs = [:]
def components = params.Componets.split(",")
stage('Build, run, report') {
    for (int i = 0; i < components.size(); ++i) {
        def index = i
        def component = components[index].trim()
        jobs[i] = {
            node {
                build job: 'Build', parameters: [string(name: 'Component', value: component)]
                build 'Run'
                build 'Reporting'
            }
        }
    }
    parallel jobs
}