marius
marius

Reputation: 1613

Get build requestor using Groovy script (Jenkins / email-ext)

I want to get the username and/or email address of the build requestor in a post-build script.

Sidenote: I want the requestor so I can set the email sender of the post-build email notification dynamically in the email-ext plugin's pre-send script.

AbstractBuild has built-in support for AbstractBuild.getCulprits() and AbstractBuild.hasParticipant(User user) but I can't find a method for retrieving the requestor. I can't find any useful reference in reference list to the User class either.

Upvotes: 4

Views: 4387

Answers (2)

xnumad
xnumad

Reputation: 15

To simply send a mail to build requestor (i.e. what you state in your sidenote to be your actual goal/problem), you can use the emailext step with requestor() in recipientProviders in the pipeline.

Example from email-ext plugin documentation:

emailext body: 'Test Message',
    recipientProviders: [developers(), requestor()],
    subject: 'Test Subject',
    to: '[email protected]'

(This feature was added after the question was posted: changelog)

Upvotes: 0

marius
marius

Reputation: 1613

I managed to solve it via the Cause of the the build, as recommended in this answer.

The reason that the build requestor can be found in the cause for a build makes perfect sense when you think about it: Not every build is directly triggered by a user. If it is triggered by a user, the list of causes for the build contains a Cause.UserIdCause, with the user's id and name.

This code snippet worked for me. It extracts the username from the build via the cause and sets the From and ReplyTo headers. I use it in the pre-send script of the email-ext Jenkins plugin.

import javax.mail.internet.InternetAddress

cause = build.getCause(hudson.model.Cause.UserIdCause.class);
username = cause.getUserName()
id = cause.getUserId()
email = new InternetAddress(String.format("%s <%[email protected]>", username, id))

msg.setFrom(email)
msg.setReplyTo(email);

Upvotes: 4

Related Questions