如何限制Jenkins跨分支并发多分支管道构建?

Lin*_*oln 5 jenkins jenkins-pipeline

有谁知道如何通过在跨分支的多分支作业中设置声明性管道来限制并发构建?

每当我们为某个阶段设置代理时,都会分配一个新的执行者。这会导致死锁,例如,当您为与执行者一样多的分支同时触发构建时。不设置代理会导致阶段随机选择执行者,这是不可接受的,因为某些阶段需要在某些代理上运行......

经典方法不起作用:

  • Throttle 并发构建插件不适用于多分支
  • 设置properties([disableConcurrentBuilds()])仅限制每个分支的并发数
  • lock步骤需要agent none在管道根中以防止分配执行器,但这会阻碍我们的全局post块执行 suff,因为它需要一个代理,并且显然无法为 post 块设置代理

小智 1

这个问题有点老了,我不确定当时是否存在解决方案,但是如果您在每个阶段设置一个代理,那么它不应该死锁,除非您依赖于另一个使用代理的构建。执行以下部分还将在与相应阶段中指定的代理相同的节点上执行 post 块。我还在最后添加了另一个管道 post 部分,如果您必须为整个管道运行 post 块并且需要让它在上一阶段使用的同一代理上运行,您可能需要它。希望这可以帮助!

def agentNameStage2 = null
pipeline {
    agent none
    stages {
        stage("Stage 1") {
            agent { label "somelabel" }
            steps {
                println getContext(hudson.model.Node)
            }
        }
        stage("Stage 2") {
            agent { label "anotherlabel" }
            steps {
                script {
                    def agentStage2 = getContext(hudson.model.Node)
                    println agentStage2

                    // Either use this hack or add whitelist hudson.model.Node getNodeName and use agentStage2.nodeName
                    //agentNameStage2 = agentStage2.nodeName // <-- Best method that needs whitelisting or to run as trusted
                    agentNameStage2 = agentStage2.toString().replaceAll('.*?\\[', '').replaceAll('\\]$', '')
                }
            }
            post {
                always {
                    // Running on an agent with "anotherlabel"
                   println getContext(hudson.model.Node)
                }
            }
        }
    }

    post {
        always {
            script {
                if(agentNameStage2) {
                    // Note this doesn't guarantee the same workspace as was used in the above Stage 2 section
                    node (agentNameStage2) {
                        println "Pipeline post is running on: " + getContext(hudson.model.Node)
                    }
                } else {
                    // Handle else case
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)