首页 > 解决方案 > 如何获取当前构建已从阶段重新启动的构建 ID?

问题描述

我有一个 Jenkins 管道,它有 5 个阶段。假设我运行它并且它的 build id 为 5,但它在第三阶段失败了。

现在我使用功能重新运行构建 5 Restart from failed stage,当前构建使用 id 7(同时有人使用 id 6 运行)。现在,在当前运行的 id 为 7 的构建中,我想获取该构建已重新启动的构建的 id(即 5)。

是否有任何 api 使用它可以获取当前构建已重新启动的构建 ID?

标签: jenkinsjenkins-pipelinejenkins-groovy

解决方案


您可以通过以下方式获取此信息currentBuild.rawBuild.getCause(RestartDeclarativePipelineCause)

工作管道示例:

pipeline{
    agent any

    stages {
        stage('Stage 1') {
            steps {
                echoRestartedInfo()
            }
        }
        stage('Stage 2') {
            steps {
                echoRestartedInfo()
            }
        }
    }
}

void echoRestartedInfo() {
    def restartCause = currentBuild.rawBuild.getCause(
        org.jenkinsci.plugins.pipeline.modeldefinition.causes.RestartDeclarativePipelineCause )

    if( restartCause ) {
        def originRunNumber = restartCause.originRunNumber
        def originStage     = restartCause.originStage
        echo "Restarted from build $originRunNumber, stage '$originStage'"
    }
    else {
        echo "Normal run"
    }
}

因为使用rawBuild它在沙盒中不起作用。将代码移动到共享库以解决此限制。


推荐阅读