Recently, I needed a mechanism to identify, as part of a try/catch block, which stage in a Jenkins Groovy Scripted Pipeline was the last to execute before the catch block was called.
Jenkins does not currently store details about the last stage to run outside of the context of that specific stage. So, in other words env.STAGE_NAME
is valid with a particular stage("I'm a stage"){ //valid here}
block, but not in, say, a catch(Exception e) { // where was I called from? }
block.
To get around this, I found a few examples, and cobbled together something that I believe will provide future functionality. I present to you the extensibleContextStage
:
// Jenkins groovy stages are somewhat lacking in their ability to persist
// context state beyond the lifespan of the stage
// For example, to obtain the name of the last stage to run,
// one needs to store the name in an ENV varialble (JENKINS 48315)
// https://issues.jenkins-ci.org/browse/JENKINS-48315
// We can create an extensible stage to provide attitional context to the pipeline
// about the state of the currently running stage.
// This also provides a capability to extend pre- and post- stage operations
// Idea / base code borrowed from https://stackoverflow.com/a/51081177/11125318
// and from https://issues.jenkins-ci.org/browse/JENKINS-48315?focusedCommentId=321366&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-321366
def call(name, Closure closure) {
env.BUILD_LAST_STAGE_STARTED = name
try {
stage(name) {
def result = closure.call()
return result
}
env.BUILD_LAST_STAGE_SUCCEEDED = name
}
catch(Exception ex) {
env.BUILD_LAST_STAGE_FAILED = name
throw ex;
}
}
This is a drop-in replacement for stage(string name){ closure}
blocks in a Jenkins Groovy Scripted Pipeline, but with the added benefit of additional environment variables:
- env.BUILD_LAST_STAGE_STARTED
- env.BUILD_LAST_STAGE_SUCCEEDED
- env.BUILD_LAST_STAGE_FAILED
So, as a full example, one can now do this (which was previously awkward):
try {
extensibleContextStage("Do some things")
{
//whatever
}
extensibleContextStage("Do some More things")
{
throw new Exception("MAYHEM!")
}
extensibleContextStage("Do some final things")
{
//whatever
}
}
catch(Exception e){
// at this point, with normal stage, we wouldn't know where MAYHEM came from,
// but with extensibleContextStage, we can look at either
// env.BUILD_LAST_STAGE_FAILED or env.BUILD_LAST_STAGE_STARTED
// to know that "Do some More things" was the offendign stage.
// this is super handy to send "helpful" notifications to slack/email
}
I hope this helps someone (if even my future self)