'Parallel stages from list in Jenkins

I have something like:

pipeline {
agent any
stages {
    stage('Run Tests') {
        parallel {
            stage ('stage1') {
                steps {
                    catchError() { 
                        build job: 'test1'}
                    catchError() { 
                        build job: 'test2'}
                }
            }
            stage ('stage2') {
                steps {
                    catchError() { 
                        build job: 'test3'}     
                    catchError() { 
                        build job: 'test4'}         
                }
            }
            stage ('stage3') {
                steps {
                    catchError() { 
                        build job: 'test5'}     
                    catchError() { 
                        build job: 'test6'}         
                }
            }
        }
    }
}

and it works fine, but I would like to modify it to optimize the duration of pipeline. So sometimes it would be to run:

  • test1 on stage1
  • test2 on stage2
  • and test3, test4, test5, test6 on stage 3

sometimes it would be to run:

  • test1, test2, test3 on stage 1
  • test4 on stage2
  • test5, test6 on stage3 etc

Is it possible to define number of stages and list of tests? In this example I would like to have 3 stages and list of 6 tests and it should works like:

  • first three tests are started parallel, each on different stage
  • after first test is finished, next test from the list is started on the same stage as finished test


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source