0
votes

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?

1
Can you glean anything from Welxome to the Matrix blog post?Ian W

1 Answers

1
votes

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