Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkins get user who aborted a build

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.

like image 679
djan Avatar asked Jul 03 '17 16:07

djan


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
}
like image 67
tofucoder Avatar answered Nov 20 '22 16:11

tofucoder


Unfortunately there seem to be no other solutions at the moment but to tweak Jenkin's code itself and a workaround.

Post-Build actionsEditable Email NotificationTriggersAdd TriggerAbortedSend ToAddRequestor → ... Jenkins Mailer Plugin:

Sends email to the user who initiated the build.

There's no Aborter to add.

http://<jenkins>/job/<project name>/lastBuild/api/xml shows:

...
<result>ABORTED</result>
...

but there's no info who aborted the build either.

A workaround could be to curl http://<jenkins>/job/<project name>/<build #> in a Post build task script and to grep for <p>Aborted by user username</p>.

like image 2
Gerold Broser Avatar answered Nov 20 '22 14:11

Gerold Broser


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"
        }
      ]
},
like image 2
grafi71 Avatar answered Nov 20 '22 16:11

grafi71