Search code examples
jenkinsgroovyjenkins-pipeline

Start multiple Jenkins jobs by loop


I want to start another Jenkins job from a job called nightly. I've created a for loop but my problem is that the loop runs only one time and then finished.

This is my code:

stage('Build_Nightly')
{
    devices = [
        'device1',
        'device2',
        'device3'
        ]
    
    for (int i = 0; i < devices.size(); i++) {

        build job: 'Build_Daily',
        parameters: 
            [
                [$class: 'StringParameterValue', name: 'Device', value: devices[i]]]
            ],
        wait: true
    }
}

The first run ist successfull and there is no second run with device2


Solution

  • check out the propagate attribute in the build step documentation.

    propagate (optional).
    If enabled (default state), then the result of this step is that of the downstream build (e.g., success, unstable, failure, not built, or aborted). If disabled, then this step succeeds even if the downstream build is unstable, failed, etc.; use the result property of the return value as needed.

    By default the propagate is set to true, which means that if the downstream build failed then the step will throw an exception thus failing the caller job. If you want to run all jobs regardless of the result you can pass the propagate attribute as false.
    if you do need to save the result of the downstream build, then the retuned value from the build command contains a result property with the downstream job result which you can then use for any logic you want.

    Example:

    stage('Build_Nightly') {
        devices = ['device1', 'device2', 'device3']
        devices.each { device ->
            def buildResults = build job: 'Build_Daily', wait: true, propagate: false,
                    parameters:[string(name: 'Device', defaultValue: device, description: '', trim: true)]
            println "The result of the downstream job is: ${buildResults.result}"
        }
    }