jenkinsjenkins-pipelinejenkins-declarative-pipeline

running the same task on multiple agents in my Jenkins declarative pipeline


I have a block like:

stage('Clone on win10x64-b-ut') {
    agent {
        node {
            label 'win10x64-b-ut'
        }
    }
    steps {
        gitClone()
    }
}    

stage('Clone on win81x64-b-ut') {
    agent {
        node {
            label 'win81x64-b-ut'
        }
    }
    steps {
        gitClone()
    }
}

I want to run the same task in somewhat like a loop by just changing the labels. I want to eliminate redundancy as much as possible.


Solution

  • Take a look at this answer: https://stackoverflow.com/a/48421660/9498358

    If you don't want to run stages in parallel (like in the linked answer), you can add a for loop inside the script block, so it will look something like this:

    def generateStage(nodeLabel) {
        return {
            stage("Clone on ${nodeLabel}") {
                agent {
                    node {
                        label nodeLabel
                    }
                }
                steps {
                    gitClone()
                }
            } 
        }
    }
    
    // ...
    
    stage('Clone') {
        steps {
            script {
                def allNodes = ['win10x64-b-ut', 'win81x64-b-ut']
    
                for (def i = 0; i < allNodes.size(); i++) {
                    generateStage(allNodes[i])
                }
            }
        }
    }