Setting Jenkins to email a build notification to the BitBucket user who pushed a branch - jenkins

A project repository has been successfully connected to a Jenkins server using the BitBucket plugin, and a project set up such that:
Each push to a branch in BitBucket will trigger a webhook sent to the Jenkins server
When the Jenkins server receives the webhook it will build the changed branch (by specifying branch name as ** in the config)
After the build is complete a notification is sent back to BitBucket of the build status using the BitBucket notifier
Each of these has been easy to set up with just the instructions in the plugin and a few quick Googles. However I've now run into a problem which is maybe more a matter of wanting to run in an unconventional manner than anything else.
Using the normal emailer plugin or the Email-ext plugin it's possible to set emails to send to people involved in the creation of a build. For example the Email-ext plugin allows choice of:
Requester
Developers (all people who have commits in the build based off its last version)
Recipient list (a pre-set list)
Various "blame" settings for broken builds
The development process being followed involves each project being worked on by one developer in a named branch, e.g. userA/projectB. Obviously other developers could check that out and push to make changes but that's frowned upon. Even in that instance, the user who pushes the change to BitBucket should be notified.
None of the current settings support this. Requester is the closest, but that only works for manual builds. It seems a very simple requirement that the push to SCM that triggered a build should notify the user who pushed, but this is not documented anywhere that is easy to find.

After a lot of searching it seems the only way to accomplish this is by using a Pre-send script. This is added to the Advanced setting of the Email-ext post-build step, and takes the form of code written in Groovy which is a Java extension.
The script can take advantage of Environment variables, but is hard to test as there's no way to run the script with these in place. You can test simple Groovy scripts from Home -> Manage Jenkins -> Script console.
One important "gotcha" with the environment variables is that they are "included" in the script, rather than variables or constants. E.g. before the script compiles and runs, the content of the variable is pasted in place of its $NAME. In the example below the multi-line string syntax is used to include the BitBicket payload, whereas it might be expected that def payload = $BITBUCKET_PAYLOAD would simply work.
import javax.mail.Message.RecipientType
import javax.mail.Address
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeMessage
import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()
def bitbucket = jsonSlurper.parseText('''
$BITBUCKET_PAYLOAD'''
)
switch (bitbucket.actor.username){
case "userA":
msg.setRecipients(MimeMessage.RecipientType.TO, InternetAddress.parse("user.a#domain.com"));
break;
case "userB":
msg.setRecipients(MimeMessage.RecipientType.TO, InternetAddress.parse("user.b#domain.com"));
break;
}
The setRecipients command overwrites any existing recipient. Thus the recipient list or other email configuration should be set as a fallback for if the user is not recognised. Additionally, if there is nobody selected to send the email to, the script won't run at all. As added debugging, including the username in the body might help.
If the script fails, stack traces should be printed to the console log output of the test, and the build pass/fail shouldn't be affected, but the normal email address setup will be used instead. In stack traces look for lines with Script() in them, as that's the container which evaluates the Groovy script.

Related

How to start a build via a phrase in Jenkins Pipelines

I am switching from the github pull request builder plugin (for security reasons) and am trying to get the same functionality from Pipelines (using different plugin). I think I have just about everything, however I can't seem to find a way to re-trigger a build simply by a trigger phrase like in github pull request builder plugin. Is that possible via pipelines?
By trigger phrase, I mean that a user can make a comment on the PR saying "Jenkins re-test" and it will kick off the build again.
You can put a condition at the top of the build script to check for the message. You can access the changesets using currentBuild.ChangeSets. The last changeset is at the end of the array. Then you need to access the last element of that changeset. Finally you can access the message via message property. You can then search for your keyword.
I am doing the opposite (not triggering the build with a phrase) but never tried for pullrequests though.
Another idea is to use the "ignore builds with specific message" property and setting this message to be a regex with look ahead that accepts everything except the keyword. I don't really recall the syntax though :/

How to instruct Jenkins to look for email template in user defined path (OTHER THAN $JENKINS_HOME/email-templates)

I have groovy email template(for Selenium Robot framework test execution) for Jenkins. Jenkins master is controlled by a remote team. So for placing this template in $JENKINS_HOME/email-templates, we need to raise a ticket and wait from 2 to 3 days. Also we expect, there might be changes required in template. So we are planning to put our templates inside our source code repository (GIT). so in the Jenkins test job, we checkout the test script together with email templates.
How to instruct Jenkins to look for the template in workspace folder instead of $JENKINS_HOME/email-templates in Jenkins Master
Sadly it seems you would need to modify the email-ext plugin as the search path is hardcoded into it.
You can see it here, check the occurrence on line 69 in file src/main/java/hudson/plugins/emailext/EmailExtTemplateAction.java
Changing it to another path would be trivial, however adding multiple locations you'd probably have to put some work in.
Edit: I wonder if it would be possible to put the wanted stuff into some txt file as a build step, and then load it into the mail content via some template configuration. If you have access to the job configuration this might be worth checking.
You can copy the template into the build workspace (e.g. with SCM step), and then email-ext can reach it:
${SCRIPT, template="${WORKSPACE}/foo.template"}

To get build status through environment variable

I am using jenkins for continous integration.
For my build purpose, i triggering email using Ant task. I am not able to find an environment variable to pass ant for sending email build status(success/failure/stable).
i want to know how can i get environment variable for build status?..if not available, what is the alternative option for build status?
Thanks in Advance
varghese
Why use ANT to send emails from Jenkins when you have two great plugins that does just that?
The default mail notification is quite good, and if you would like to have more control
I suggest using the Email-ext plugin which is very comprehensive.
If still wish to use ANT to sent your mail-notifications including the status
you will have to break your process into two steps,
where the first part runs the build and the second one runs the ANT script to report the status.
In this case, you will need to trigger the second job from the first job via the Parameterized Build plugin -
see my answer here:
trigger other configuration and send current build status with Jenkins
The build status is not set until the job has finished running, so there is no easy way to push build status to a process triggered within the build itself. You could pull build status via the API, but this would have to be an externally triggered process due to the constraint mentioned above. Any reason you aren't using the built in email support or one of the excellent email extension plugins such as this one?

Jenkins - Trigger email based on input parameter

I have several Jenkins jobs where I want an email to be triggered (or not trigger) based on an input parameter.
The use case is that I have one deploy job per project, but that job is parametrized for each environment. We you run the job you can select which environment to deploy to (Dev1, Dev2, QA, etc). Ideally I would like to send out notification emails when a new build is sent to QA, but I do not want to send out notification emails when a new build is sent to Dev, because that happens all the time (with every developer commit) and would flood email boxes.
I've tried googling but haven't yet found a solution. I am currently using the email-ext plugin.
Thanks.
It is a very nasty way to solve the problem, but if you cannot do it by any other means...
Create a dependent job that exists primarily to pass / fail based on the value of the parameter, which would get passed as a parameter to the job. Then you could chain the decision the job made to the email notification.
Of course, if you were going to do this, it would probably be better to just write a small parametrized email sender using javax.mail and have Jenkins run it by "building" an ANT project that actually calls the "java" task. Then you have your own email sender (full control) and could make it a dependent job on the other tasks.
I hope someone chimes in with a simpler way...
In email-ext you can add a "Script - Before Build" or a "Script - After Build" trigger which will trigger on whether the specified groovy script returns true or false.
The help for the script reads:
Use this area to implement your own trigger logic in groovy. The last line will be evaluated as a boolean to determine if the trigger should cause an email to be sent or now.
They don't give many details of what's available in the script, but from the source code on Github, it looks like you have "build" and "project" at least, and some common imports done for you:
cc.addCompilationCustomizers(new ImportCustomizer().addStarImports(
"jenkins",
"jenkins.model",
"hudson",
"hudson.model"));
Binding binding = new Binding();
binding.setVariable("build", build);
binding.setVariable("project", build.getParent());
binding.setVariable("rooturl", JenkinsLocationConfiguration.get().getUrl());
binding.setVariable("out", listener.getLogger());
Caveat, I haven't tried this, but this should work as an example script:
build.buildVariables.get("MY_DEPLOYMENT_ENV") == "QA"
that should get the value of a String or Choice parameter you've created called "MY_DEPLOYMENT_ENV" and trigger the email if the current value is "QA"

Provide userName and shortDescription in Jenkins remote API job triggering

I know how to provide build parameters:
wget --post-data='json={"parameter": {"name": "testparam", "value": "HELLO"}}' http://jenkins/job/Job1/build?delay=0sec
But, is it possible to provide a shortDescription and userName in a Jenkins remote API build request via wget/curl?
How should it look like in json or xml? Is there any manual/guidance on the net?
I will use this in along with the problem described in Trigger dynamic set of jobs. I want to provide triggered job with the calling job name and build number.
You may consider using Jenkins CLI (http://[jenkins-host]/cli for help in the browser). You can specify a user to a build CLI command. I'm not sure what you mean by short description when starting a build, though.
Update: Please see Jenkins Wiki Authenticating Scripted Clients. I've created a user foobar ('full name' Foo Bar) and tried the following:
wget --auth-no-challenge --http-user=foobar --http-password=[apiToken] http://jenkins.yourcompany.com/job/your_job/build
Where the token is obtained from user configuration page: http://localhost:8081/user/foobar/configure. It worked. The user has to exist, though. Also, you must specify --auth-no-challenge option, otherwise it kicks off the build as anonymous. The status description says Started by user Foo Bar.
Another Update If everything else fails, you may consider the following workaround: start all builds via the Parameterized Trigger Plugin with an additional boolean parameter that tells the triggered job whether to run or not. In case the job is asked not to run it would fail immediately and call a 'clean-up' job passing to it the build info; the clean-up job then will delete the build from the system.

Resources