reachit
reachit

Reputation: 63

How to enforce jenkins job to wait until all jobs executed in loop

In this i have requirement to trigger my job with 3 iterations (below example 3) without waiting, but after all 3 jobs were triggered this has to wait until all 3 jobs have successfully finished irrespective of fail or pass.

I am using wait:true but that will wait for each iteration, thats not i want. If I use wait:false , it's not waiting once all iterations in loop has completed, its not waiting for the downstream jobs to finish. I want the current job to wait until i got result of jobs (3 pipelines).

//job1 is a pipeline job which i am triggering multiple times with different params

stage {
    for(int cntr=0;i<3;i++) {
         build job : "job1",
         parameters: [string(name: 'param1', value:val[cntr] )],
         wait: false
    }
}

Upvotes: 1

Views: 4878

Answers (1)

Noam Helmer
Noam Helmer

Reputation: 6849

I think what you actually want is to run them all in parallel and then wait until they all finish.
To do so you can use the parallel keyword:

parallel: Execute in parallel. Takes a map from branch names to closures and an optional argument failFast >which will terminate all branches upon a failure in any other branch:

parallel firstBranch: {
    // do something
}, secondBranch: {
    // do something else
},
failFast: true|false```

In your case it can look something like:

 stage('Build Jobs') {
     def values = ['value1', 'value2', 'value2']
     parallel values.collectEntries {value ->
         ["Building With ${value}": {
             build job : "job1",
                   parameters: [string(name: 'param1', value: value)],
                   wait: true
         }]
     }
 }

Or if you want to use indexes instead of a constant list:

    stage('Build Jobs') {
        def range = 0..2 //  or range = [0, 1, 2]
        parallel range.collectEntries { num ->
            ["Iteration ${num}": {
                build job : "job1",
                      parameters: [string(name: 'param1', value: somefunc(num)],
                      wait: true
            }]
        }
    }

This will execute all the jobs in parallel and then wait until they are all finished before progressing with the pipeline (don't forget to set the wait parameter of the build step to true).
You can find more examples for things like this here.

Upvotes: 5

Related Questions