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

How to limit Jenkins concurrent multibranch pipeline builds?

我正在考虑在 Jenkins 中将并发构建的数量限制为特定数量,利用多分支管道工作流,但在文档或 google.[= 中没有找到任何好的方法来做到这一点15=]

一些文档说这可以在 Jenkinsfile 的 stage 步骤中使用并发来完成,但我也 read elsewhere 认为这是一种不推荐的方式。

看起来 something released fairly recently for limiting concurrency via Job Properties but I couldn't find documentation for it and I'm having trouble following the code. The only thing I found a PR 显示了以下内容:

properties([concurrentBuilds(false)])

但我无法正常工作。

有没有人知道或有一个很好的例子来说明如何限制给定的多分支项目的并发构建数量?也许是 Jenkinsfile 片段显示了如何限制或限制多分支并发构建的数量?

找到我要找的东西。您可以在 Jenkinsfile.

中使用以下块限制并发构建
node {
  // This limits build concurrency to 1 per branch
  properties([disableConcurrentBuilds()])
  
  //do stuff
  ...
}

同样可以用声明性语法实现:

pipeline {
    options {
        disableConcurrentBuilds()
    }
}

正如@VadminKotov 指出的那样,也可以使用 jenkins 声明式管道禁用并发构建:

pipeline {
    agent any
    options { disableConcurrentBuilds() }
    stages {
        stage('Build') {
            steps {
                echo 'Hello Jenkins Declarative Pipeline'
            }
        }
    }
}

disableConcurrentBuilds

Disallow concurrent executions of the Pipeline. Can be useful for preventing simultaneous accesses to shared resources, etc. For example: options { disableConcurrentBuilds() }

使用 Lockable Resources 插件 (GitHub) 可以限制并发构建或阶段。我总是使用这种机制来确保不会同时执行 publishing/release 步骤,而可以同时构建正常阶段。

echo 'Starting'
lock('my-resource-name') {
  echo 'Do something here that requires unique access to the resource'
  // any other build will wait until the one locking the resource leaves this block
}
echo 'Finish'

谢谢Jazzschmidt, I looking to lock all stages easily, this works for me ()

pipeline {
  agent any
  options {
    lock('shared_resource_lock')
  }
  ...
  ...
}