如何在Jenkins声明式管道中多Agent循环执行同一任务?
Refactoring Redundant Jenkins Stages with a Loop
Nice catch on the redundant code—let's refactor this to be cleaner and easier to maintain! The core idea is to define your target node labels in a list, then loop through that list to dynamically generate each stage, eliminating the need to repeat the same stage structure over and over.
Basic Sequential Loop Version
This will run each clone stage one after another:
pipeline { agent none stages { script { // Define all your target node labels in one place def targetNodes = ['win10x64-b-ut', 'win81x64-b-ut'] targetNodes.each { nodeLabel -> stage("Clone on ${nodeLabel}") { agent { node { label nodeLabel } } steps { gitClone() } } } } } }
Key Details:
- We centralize all node labels in the
targetNodeslist—adding a new node later is as simple as inserting a new string here, no more copying entire stage blocks. - The
scriptblock is required in declarative pipelines to use Groovy's dynamic looping features (since declarative is static by default). - Each iteration generates a stage with a unique name (using the node label) and targets the correct agent automatically.
Optional Parallel Execution Version
If your Jenkins environment allows running these jobs simultaneously, you can refactor to run the clone stages in parallel to save time:
pipeline { agent none stages { stage('Parallel Clone on All Nodes') { parallel { script { def targetNodes = ['win10x64-b-ut', 'win81x64-b-ut'] targetNodes.each { nodeLabel -> // Dynamically create a parallel branch for each node "${nodeLabel}" { agent { node { label nodeLabel } } steps { gitClone() } } } } } } } }
This wraps all the clone operations into a single parent stage and runs them in parallel, which is great if you have the resources to speed up your pipeline.
内容的提问来源于stack exchange,提问作者vmwgeek
相关产品推荐
相关产品推荐

