Jenkins Pipeline使用catchError后获取当前舞台状态

这是我前面的问题的后续内容:

Set a stage status in Jenkins Pipelines

事实证明,如果我想通过catchError进行如下操作,我可以将管道保持为SUCCESS,但可以将单个阶段标记为UNSTABLE:

node()
{
    stage("Stage 1")
    {
        catchError(buildResult: 'SUCCESS',stageResult: 'UNSTABLE')
        {
            sh 'exit 1'
        }
    }
}

如果我想获取管道本身的当前状态,可以使用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
    }
}

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

因此,catchError()基本上不错,但是我想知道如果更改后如何将状态更改捕获到我的阶段...有人知道您如何访问当前阶段的状态吗?从管道进入吗?

guoqia 回答:Jenkins Pipeline使用catchError后获取当前舞台状态

我是这样做的(以保持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 {
                }
            }
        }
    }
}
,

尽管到目前为止,还没有直接方法可以访问管道中某个阶段的结果,但是您可以解决该问题。这是考虑到您仅对问题中的SUCCESSUNSTABLE阶段结果感兴趣,而对FAILURE却不感兴趣。

解决方法是在管道顶部初始化一个空映射,以存储每个阶段的结果。现在,将catchError()方法与try-catch块结合使用,而不是unstable()方法。这是因为后者不仅使您可以将结果设置为不稳定,而且还可以执行其他操作,例如将结果添加到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
    }
}
,

作为添加到Dibakar Aditya答案的替代方法,可以将所有内容包装在类似于常规步骤的函数中。即:

void
,

对于我来说,最优雅的方法是post部分。 在您的示例中,您将舞台标记为UNSTABLE,因此之后可以使用post->unstable捕获它。

stage("1") {
    steps {
        catchError(buildResult: 'SUCCESS',stageResult: 'UNSTABLE') {
            error 'Something goes wrong'
        }
    }
    post {
        always { echo 'Executed on every build'}
        unstable { echo 'Executed only if build is unstable (marked by catchError)'}
    }
}
本文链接:https://www.f2er.com/3149861.html

大家都在问