简体   繁体   中英

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.

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[i]; i++) {
                generateStage(allNodes[i])
            }
        }
    }
}

Accepted answer is not working. Expecially the def part.

This is working:

def generateStage(nodeLabel) {
    stage("Runs on ${nodeLabel}") {
        node(nodeLabel) {
            sh 'hostname'
        }
    }
}

pipeline {
    agent {
        node {
            label '!docker'
        }
    }
    stages {
        stage('Run') {
            steps {
                script {
                    nodes = nodesByLabel(label: 'docker')

                    for (node in nodes) {
                        generateStage(node)
                    }
                }
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM