Jenkins get user who aborted a build

Viewed 4731

Is there a way to get the username when a build is aborted by a user? Preferably using jenkins pipeline code.

When a build is aborted by a user, it logs:

Aborted by <username>

so I hope it is stored as a variable for a brief period.

Use case: username to be later used to inform the user itself or other users via email or other means of messaging.

3 Answers

It seems that a InterruptedBuildAction object is inserted in to the list of build action if a job is aborted. This object can be used to retrieve the user that aborted the build. I use the following function in my Jenkinsfile:

@NonCPS
def getAbortUser()
{
    def causee = ''
    def actions = currentBuild.getRawBuild().getActions(jenkins.model.InterruptedBuildAction)
    for (action in actions) {
        def causes = action.getCauses()

        // on cancellation, report who cancelled the build
        for (cause in causes) {
            causee = cause.getUser().getDisplayName()
            cause = null
        }
        causes = null
        action = null
    }
    actions = null

    return causee
}

In fact you can have this information with the REST API, just use the following URL with an appropriate build:

/api/json?tree=actions[causes[*]]&pretty=true

And you should be able to find the requested information under actions[causes], e.g.:

{
    "_class" : "jenkins.model.InterruptedBuildAction",
    "causes" : [
        {
          "_class" : "jenkins.model.CauseOfInterruption$UserInterruption",
          "shortDescription" : "Aborted by some_user_name"
        }
      ]
},
Related