Pipeline - Parallel execution of tasks

Issue

  • Want to execute parallel tasks in Pipeline

Environment

Resolution

Following a couple of options to achieve it.

Disclaimer: Please note that the above script just has been proved/tested within the specified environment. In the case a particular step does work within your environment, please go to <JENKINS_URL>/pipeline-syntax/ validate the syntax of the problematic step with the output from the Snippet Generator.

Option 1

def tasks = [:]

tasks["task_1"] = {
  stage ("task_1"){    
    node('label_example1') {  
        sh 'echo $NODE_NAME'
    }
  }
}
tasks["task_2"] = {
  stage ("task_2"){    
    node('label_example2') {  
        sh 'echo $NODE_NAME'
    }
  }
}

parallel tasks

Option 2

def testList = ["a", "b", "c", "d"]
def branches = [:] 

for (int i = 0; i < 4 ; i++) {
       int index=i, branch = i+1
       stage ("branch_${branch}"){ 
            branches["branch_${branch}"] = { 
                node ('label_example'){
                    sh "echo 'node: ${NODE_NAME},  index: ${index}, i: ${i}, testListVal: " + testList[index] + "'"
                }
            }
      }
}

parallel branches

Note: Variables define outside the for block are not local, but global to the script. Testing the option 2, you will notice that variable i prints always value 4, whereas index increases from 0 to 3 and branch from 1 to 4.

References

Have more questions? Submit a request

0 Comments

Please sign in to leave a comment.