如何在Jenkins声明式管道

时间:2020-02-02 12:30:42

标签: jenkins groovy parallel-processing jenkins-pipeline jenkins-declarative-pipeline

在声明式管道中并行执行函数的正确方法是什么?

此论坛上的几则帖子都建议您构建一个数组,并将该数组传递给“ parallel”或将一个函数传递给“ parallel”

Is it possible to create parallel Jenkins Declarative Pipeline stages in a loop?

Simple parallel execution in Jenkins for an array

我已经做了几次尝试使其正常工作,但是它始终以串行方式运行

我认为问题在于,即使在我达到阶段的“并行”步骤之前,在构建数组时也会对函数进行评估。

我无法从官方文档中找到解决方案。

https://jenkins.io/blog/2017/09/25/declarative-1/

这是我希望它工作的方式,但是有可能吗?

    pipeline {

        agent {
            label "l1" && "l2"
        }

        stages {

            stage ('Prepare Data') {
                // Some code that creates that data object
                // data is an array of maps
                data
            }

            stage ('Build') {
                script {
                    def stepsForParallel = [:]
                    data.each { d ->
                        // name is a key in the data map
                        stepsForParallel["${d['name']}"] = {
                            node {
                                stage("${d['name']}") {
                                    stepsForParallel[execDownStreamJob("DownStreamJobName", d)] = {
                                        println("Executing DownstreamJob")
                                    }
                                }
                            }
                        }
                    }
                    parallel stepsForParallel
                }
            }

        }
    }
}

下面的函数实际上不在这个问题的范围内,但是我添加了它,以防它提供某些价值。这篇文章对此做了最好的解释:https://stackoverflow.com/a/42248825/5006720

// job is a string
// jobParameters is a hashmap
def execDownStreamJob(job, jobParameters) {

    // Some parsing takes place on hashMap and creates the p object 
    // 'p' is passed to the 'build job' function as a parameter

    def downStreamJobResult = build job: job, parameters: p, propagate: false

    // Some try/catch logic

}

1 个答案:

答案 0 :(得分:0)

下面的代码部分真的很奇怪

因为您尝试分配两次stepsForParallel

    stepsForParallel["${d['name']}"] = {
        node {
            stage("${d['name']}") {
                stepsForParallel[execDownStreamJob("DownStreamJobName", d)] = {
                    println("Executing DownstreamJob")
                }
            }
        }
    }

我认为它应该看起来像这样(目前无法测试):

    script {
        def stepsForParallel = data.collectEntries{ d ->
            ["${d.name}", 
                {
                    stage("${d.name}") {
                        println "DownstreamJob ${d.name} start")
                        execDownStreamJob("DownStreamJobName", d)
                        println "DownstreamJob ${d.name} end")
                    }
                }
            ]
        }
        parallel stepsForParallel
    }