Jenkins Pipeline 在使用 catchError 后获取当前阶段状态

TxA*_*G98 10 jenkins jenkins-pipeline

这是我之前问题的后续:

在 Jenkins Pipelines 中设置阶段状态

事实证明,我可以将管道保持为成功,但如果我想通过catchError这样的方式,可以将单个阶段标记为不稳定:

node()
{
    stage("Stage 1")
    {
        catchError(buildResult: 'SUCCESS', stageResult: 'UNSTABLE')
        {
            sh 'exit 1'
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我想获取管道本身的当前状态,我可以使用currentBuild.getCurrentResult(),但我没有看到currentStage类似的情况。

我有兴趣尝试一种在我的阶段可能看起来像这样的模式:

stage("1") {
    catchError(buildResult: 'SUCCESS', stageResult: 'UNSTABLE') {
        // do stuff
    }
    // perhaps more catchError() blocks
    if(currentStage.getCurrentResult() == "UNSTABLE") {
        // do something special if we're unstable
    }
}
Run Code Online (Sandbox Code Playgroud)

但这会失败,因为没有currentStage可用的。

所以基本上,catchError()很好,但我想知道如果我的阶段发生变化,我如何捕获状态变化...有谁知道如何从管道访问当前阶段的状态?

小智 7

我这样做了(为了保留catchError):

def boolean test_results = false

pipeline {
    ...
    stage( 'x' ) {
        steps{
            catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
                
                <Do some dangerous stuff here>
                
                //
                // If we reached here the above step hasn't failed
                //
                script { test_results = true }
            }
        }
    }
    stage( 'y' ) {
        steps{
            script{
                if( test_results == true ) {
                } else {
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Dib*_*tya 4

尽管目前还没有直接的方法来访问管道中某个阶段的结果,但您可以解决它。这是考虑到您只对问题中的任一SUCCESS或阶段结果感兴趣,而不是对.UNSTABLEFAILURE

解决方法是在管道顶部初始化一个空映射来存储每个阶段的结果。现在,不再使用该catchError()方法,而是将该unstable()方法与 try-catch 块结合使用。这是因为后者不仅可以让您将结果设置为不稳定,还可以执行其他操作,例如将结果添加到 except 块中的映射中。然后您可以从语句中的地图中读取此存储的结果if

例子

stageResults = [:]
...
stage("1") {
    try {
        // do stuff
        // Add to map as SUCCESS on successful execution 
        stageResults."{STAGE_NAME}" = "SUCCESS"
    } catch (Exception e) {
        // Set the result and add to map as UNSTABLE on failure
        unstable("[ERROR]: ${STAGE_NAME} failed!")
        currentBuild.result = "SUCCESS"
        stageResult."{STAGE_NAME}" = "UNSTABLE"
    }
    if(stageResults.find{ it.key == "{STAGE_NAME}" }?.value == "UNSTABLE") {
        // do something special if we're unstable
    }
}
Run Code Online (Sandbox Code Playgroud)