Issue
How do I report the stage in which a declarative pipeline failed? In the fail block, I want to get failedStage.name and report it (eventually to slack).
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?'
}
}
}
Solution
PipelineVisitor is a fine approach. However, if you want to see just the errors, then leveraging FlowGraphTable
might be even better.
The following provides a list of maps for each failed steps, and traverses the downstream jobs as well. I find it to be pretty useful.
You'll want to use a shared library to avoid the security sandbox warnings / approvals
List<Map> getStepResults() {
def result = []
WorkflowRun build = currentBuild()
FlowGraphTable t = new FlowGraphTable(build.execution)
t.build()
for (def row in t.rows) {
if (row.node.error) {
def nodeInfo = [
'name': "${row.node.displayName}",
'url': "${env.JENKINS_URL}${row.node.url}",
'error': "${row.node.error.error}",
'downstream': [:]
]
if (row.node.getAction(LogStorageAction)) {
nodeInfo.url += 'log/'
}
for (def entry in getDownStreamJobAndBuildNumber(row.node)) {
nodeInfo.downstream["${entry.key}-${entry.value}"] = getStepResults(entry.key, entry.value)
}
result << nodeInfo
}
}
log(result)
return result
}
Map getDownStreamJobAndBuildNumber(def node) {
Map downStreamJobsAndBuilds = [:]
for (def action in node.getActions(NodeDownstreamBuildAction)) {
def result = (action.link =~ /.*\/(?!\/)(.*)\/runs\/(.*)\//).findAll()
if (result) {
downStreamJobsAndBuilds[result[0][1]] = result[0][2]
}
}
return downStreamJobsAndBuilds
}
Answered By - Peter Kahn