kenorb kenorb - 1 month ago 23
Groovy Question

How to make Pipeline job to wait for all triggered parallel jobs?

I've Groovy script as part of the Pipeline job in Jenkins as below:

node {
stage('Testing') {
build job: 'Test', parameters: [string(name: 'Name', value: 'Foo1')], quietPeriod: 2, wait: false
build job: 'Test', parameters: [string(name: 'Name', value: 'Bar1')], quietPeriod: 2, wait: false
build job: 'Test', parameters: [string(name: 'Name', value: 'Baz1')], quietPeriod: 2, wait: false
build job: 'Test', parameters: [string(name: 'Name', value: 'Foo2')], quietPeriod: 2, wait: false
build job: 'Test', parameters: [string(name: 'Name', value: 'Bar2')], quietPeriod: 2, wait: false
build job: 'Test', parameters: [string(name: 'Name', value: 'Baz2')], quietPeriod: 2, wait: false
}
}


which executes multiple other freestyle jobs in parallel, because of
wait
flag being set to
false
. However I'd like for the caller job to finish when all jobs are finished. Currently the Pipeline job triggers all the jobs and finishes it-self after few seconds which is not what I want, because I cannot track the total time and I don't have ability to cancel all triggered jobs at one go.

How do I correct above script for Pipeline job to finish when all jobs in parallel are completed?

I've tried to wrap build jobs in
waitUntil {}
block, but it didn't work.

Answer

You should use pipeline parallel expression, which will wait for all spawned jobs / subtasks to complete:

stage('testing') {
    def branches = [:]

    for(i = 0; i < params.size(); i += 1) {
        def param = params[i]

        branches["Test${i}"] = {
            build job: 'Test', parameters: [string(name: 'Name', value: param)], quietPeriod: 2
        }
    }
    parallel branches
}

You can find some more examples in pipeline docs at jenkins.io

Comments