在 Jenkins 中锁定并行阶段

Locking parallelised stages in Jenkins

我们正在尝试编写一个声明性的 Jenkinsfile 构建脚本,以便 运行 在几个阶段的每个阶段并行执行多个步骤,但是我们需要防止多个构建同时 运行ning因为它们依赖于相同的资源。因此,我们尝试使用 locking 锁定所有阶段,以便构建可以在另一个构建尝试使用相同资源之前完全完成。

但是,我们发现锁定阶段需要 并且并行步骤 只能包含在顶级阶段 中: WorkflowScript: 24: Parallel stages or branches can only be included in a top-level stage

基本上我们要做的是:

#!/usr/bin/env groovy

pipeline {
    agent any

    stages {
        stage('parent') {
            options {
                lock('resource')
            }
            stages {
                stage('build') {
                    steps {
                        parallel( 
                            'app1': { build("app1") },
                            'app2': { build("app2") },
                        )
                    }
                }

                stage('deploy') {
                    steps {
                        parallel(
                            'app1': { deploy("app1") },
                            'app2': { deploy("app2") },
                        )
                    }
                }
            }
        }
    }
}

是否有解决此问题的方法?

这能解决您的问题吗?

pipeline {
    agent any
    options {
        lock('resource')
    }
    stages {
        stage('build') {
            parallel {
                stage('app1') {
                    steps {
                        echo("build app1")
                    }
                }
                stage('app2') {
                    steps {
                        echo("build app2") 
                    }
                }
            }
        }
        stage('deploy') {
            parallel {
                stage('app1') {
                    steps {
                        echo("deploy app1")
                    }
                }
                stage('app2') {
                    steps {
                        echo("deploy app2") 
                    }
                }
            }
        }
    }
}

您可能需要更新到 latest pipeline code 这会锁定整个作业的资源。如果你想为每个并行阶段锁定资源,我建议阶段不是并行的