You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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 targetNodes list—adding a new node later is as simple as inserting a new string here, no more copying entire stage blocks.
  • The script block 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:46:20