Seth Lutske
Seth Lutske

Reputation: 10752

Quicker syntax for Jenkins identical parallel stages

I have some parallel stages in my Jenkins pipeline. They are all identical, except that they run on different agents:

stage {
    parallel {
        stage {
            agent {
                label 'agent-1'
            }
            steps {
                sh 'do task number 468'
            }
        }
        stage {
            agent {
                label 'agent-2'
            }
            steps {
                sh 'do task number 468'
            }
        }
        stage {
            agent {
                label 'agent-3'
            }
            steps {
                sh 'do task number 468'
            }
        }
    }
}

I want to add more parallel stages on more nodes, but the script is long and repetetive. What's the best way to rewrite this to tell jenkins to parallelize the same steps across agents 1, 2, 3, 4...etc?

Upvotes: 0

Views: 188

Answers (1)

Altaf
Altaf

Reputation: 3086

Please see below code which will create and run the stage on multiple agents:

// Define your agents
def agents  = ['agent-1','agent-2','agent-3']

def createStage(label) {
    return {
        stage("Runs on ${label}") { 
            node(label) {
                // build steps that should happen on all nodes go here
                echo "Running on ${label}"
                sh 'do task number 468'
            }
        }
    }
}

def parallelStagesMap = agents.collectEntries {
    ["${it}" : createStage(it)]
}
pipeline {
    agent none
    stages {
         stage('parallel stage') {
            steps {
                script {
                    parallel parallelStagesMap
                }
            }
        }        
    }
}


More information is available at : Jenkins examples

Upvotes: 1

Related Questions