Repeat build n times in Jenkins

jenkins

Solution

It is possible to create a repeated loop (not infinite) of a Jenkins job, by adding a conditional step that evaluates a $JOB_COUNTER parameter, which simply being decreased on each iteration.

To do so, first create a new String parameter "JOB_COUNTER" with default value = 1.

Then use EnvInject plugin, and check "Prepare an environment for the run" + "Override Build Parameters", and add in "Evaluated Groovy script":

def map  = [:]
int newJobCounter = JOB_COUNTER.toInteger() - 1
println "Decreasing JOB_COUNTER from " + JOB_COUNTER + " to " + newJobCounter  
map.put("JOB_COUNTER", newJobCounter)
return map

Finally, with Conditional BuildStep plugin + Parameterized Trigger plugin (and optionally with PostBuildScript plugin, if you'd like to start next iteration only after build has completed), set the following:

UPDATE:

Another way to loop, is to decrease JOB_COUNTER in the predefined parameters (instead of inside EnvInject):

JOB_COUNTER=${JOB_COUNTER}-1

Then, to correctly update JOB_COUNTER on each iteration, use evaluate() method instead of toInteger(), in the EnvInject groovy:

int newJobCounter = evaluate(JOB_COUNTER)
println "Evaluating JOB_COUNTER: " + JOB_COUNTER + " => " + newJobCounter  
map.put("JOB_COUNTER", newJobCounter)

And finally, the Conditional action should be:

$JOB_COUNTER > Greater than 1

Problem

Is there any way to repeat a build N times? (doesn't matter the status of the last build). The build is parametrized and for the moment I am using Jenkins Parameterized Trigger plugin which is set to trigger the same build, but this is of course an infinite loop. I would like to be able to specify how many times to repeat the build with the same parameters.

Original source