我如何报告declarative pipeline的阶段失败了?在失败块中,我想获取 failedStage.name 并报告它(最终松懈)。
pipeline {
agent { label 'master'}
stages {
stage('Ok') {
steps {
echo 'do thing'
}
}
stage('NotOK') {
steps {
sh 'make fail'
}
}
}
post {
always {
echo 'ok'
}
failure {
echo 'Failed during Which Stage?'
}
}
}
最佳答案
概述
这通常可以使用 Blue Ocean 插件 API 来实现。类(class) PipelineNodeGraphVisitor
可用于迭代所有流水线节点(例如阶段、并行分支和步骤)。我们只需要检查 type
是否 FlowNodeWrapper
的属性(property)等于 FlowNodeWrapper.NodeType.STAGE
.
此外,我们可以从 ErrorAction
中获取失败原因。 s 存储在节点中。
代码
您通常会将以下代码放入共享库中,
因为如果直接插入到管道代码中,它会阻止管道在沙箱环境中运行。
import io.jenkins.blueocean.rest.impl.pipeline.PipelineNodeGraphVisitor
import io.jenkins.blueocean.rest.impl.pipeline.FlowNodeWrapper
import org.jenkinsci.plugins.workflow.support.steps.build.RunWrapper
import org.jenkinsci.plugins.workflow.actions.ErrorAction
// Get information about all stages, including the failure causes.
//
// Returns a list of maps: [[id, displayName, result, errors]]
// The 'errors' member is a list of unique exceptions.
@NonCPS
List<Map> getStageResults( RunWrapper build ) {
// Get all pipeline nodes that represent stages
def visitor = new PipelineNodeGraphVisitor( build.rawBuild )
def stages = visitor.pipelineNodes.findAll{ it.type == FlowNodeWrapper.NodeType.STAGE }
return stages.collect{ stage ->
// Get all the errors from the stage
def errorActions = stage.getPipelineActions( ErrorAction )
def errors = errorActions?.collect{ it.error }.unique()
return [
id: stage.id,
displayName: stage.displayName,
result: "${stage.status.result}",
errors: errors
]
}
}
// Get information of all failed stages
@NonCPS
List<Map> getFailedStages( RunWrapper build ) {
return getStageResults( build ).findAll{ it.result == 'FAILURE' }
}
演示管道
pipeline{
agent any
stages {
stage('SuccessStage') {
steps {
echo 'Success'
}
}
stage('FailedStage') {
steps {
readFile 'dfgkjsdffj'
}
}
stage('SkippedStage') {
steps {
echo 'Skipped because of error in FailedStage'
}
}
}
post {
failure {
script {
// Print information about all failed stages
def failedStages = getFailedStages( currentBuild )
echo "Failed stages:\n" + failedStages.join('\n')
// To get a list of just the stage names:
//echo "Failed stage names: " + failedStages.displayName
}
}
}
}
蓝色海景
笔记
如果您想获得除
FAILURE
以外的其他结果的阶段,看看我的函数getFailedStages()
.您可以简单地更改条件,例如。例如:it.result in ['FAILURE','UNSTABLE']
it.result != 'SUCCESS'
可能的替代实现:
严格来说,Blue Ocean API 不是必需的。它只是简化了很多代码。你可以只使用基本的 Jenkins 管道 API 来做同样的事情。作为起点,寻找
FlowGraphWalker
用于迭代管道节点。看看蓝海的代码PipelineNodeGraphVisitor
找出他们如何确定“阶段”节点类型。
关于jenkins - 确定 Jenkins 声明式管道中的失败阶段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43439093/