chenchuk
chenchuk

Reputation: 5742

Dynamically generated parallel block in jenkins pipeline

Im using Jenkins pipeline to do some build/deploy tasks simultaneously using the 'parallel' construct :

stage('tasks')
  parallel('task1': {someFunction(arg=1)}, 
           'task2': {someFunction(arg=2)},
           'task3': {someFunction(arg=3)}
  )
}

sometimes i would like to build this construct dynamically during runtime. is it possible ?

example: file to copy for selected targets from a list of 10.

when user choose 4 items i want to create a 'parallel' structure with 4 items and then execute it.

Upvotes: 0

Views: 53

Answers (1)

lenkovi
lenkovi

Reputation: 1798

Basically you could create a function which returns a map of groovy closures holding the tasks for your items.

Bear in mind that you need to turn off groovy sandboxing to be able to run this.

#!/usr/bin/env groovy

def getSomeFunction = { arg ->
    // returns the closure with your task, function, run with the chosen parameter
    return {
        println(arg)
    }
}

def getParalellBlock = { number ->
    def  myList =  ['a', 'b', 'c', 'd'] // your list of items
    def blockMap = [:]
    1.upto(number, {
        // Make sure to handle 'index out of range' kind of problems
        blockMap.put(it.toString(), getSomeFunction(myList[it-1]))
    })
    return blockMap
}

node() {
    stage('tasks') {
        // you can supply the parameter from job parameters
        parallel(getParalellBlock(3))
    }
}

Upvotes: 1

Related Questions