Send Email to person on build failure on his commits - jenkins

I want to Send Email specific to a person who's changes caused build failure.

Have you looked up at email-ext plugin?
At post you can set up the trigger failure:
post {
failure {
emailext body: "$env.BODY_CONTENT",
mimeType: 'text/html',
recipientProviders: [requestor(), developers(), culprits()]
subject: '$DEFAULT_SUBJECT',
to: env.PROJECT_RECIPIENTS
}
}
Make sure to configure email-ext plugin.
recipientProviders will add destinations based on:
requestor: the person who started the build
developers: to every person who commit to the repo
culprits: to every person who commit since last non-broken build
You can remove developers and requestor, culprits is the option you're looking for. You can also remove to:

Related

email on jenkins user input

I have a jenkins pipeline where I wait for user input to proceed or abort. Is there any way I can send the same in email to let the concerned person aware and he can click on the email to procceed Or abort the pipeline.?
It is possible to execute such action by using Jenkins API, this can be achieved using Jenkins Rest Api you can check this SO question.
I haven't tried this solution yet but I guess this pipeline could help you get a better idea of how I would think about implementing such behavior in a pipeline like this:
pipeline {
agent any
stages {
stage('Mail Notification') {
steps {
echo 'Sending Mail'
mail bcc: '',
body: 'Stop job through this link: ${env.BUILD_URL}/job/${env.JOB_NAME}/${env.BUILD_NUMBER}/stop',
cc: '',
from: '',
replyTo: '',
subject: 'Jenkins Job',
to: 'example#domain.com'
}
}
}
}
Jenkins pipeline is aware of such variables like ${env.BUILD_URL} ${env.JOB_NAME} ${env.BUILD_NUMBER}

Send Slack notification from Jenkins into private channel of other users

What i did:
I managed to send Notifications with Status of every Build to my private Slack Channel. So i configured my Jenkins as well as my Slack app.
What i want to do:
Sending messages to other users private Channels.
What i have tried:
I added channels to my Jenkinsfile and checked them in the Slack App of Jenkins and it wasn't successful. I think i have to create sth like a Bot, which is in the specific Channel i want to send a message to. Very sure that Jenkins can't see the channel because its a private channel of another person(obviously) and is not able to find it. Couldn't find a solution for this Problem.
Thanks a lot for your help, i think i wasted way to much time trying to find an answer for that.
I setup our build pipeline to send Slack notifications to commit authors. The biggest challenge is mapping to the Slack username. I had every developer on the team change their git user.name to match their Slack Display name. This is the most straight-forward way I know to make this work.
git config --global user.name "Mona Lisa" where "Mona Lisa" is the Slack display name of the user.
In the Jenkins pipeline, I used env.GIT_COMMIT_AUTHOR to get this value back.
Note, that the environment variable provides the commit author at the HEAD of whatever was checked out. For pull requests in a multi-branch pipeline, if the PR is not a fast forward, the commit is what the merge would produce, resulting in an author of 'Jenkins'. So, in that case, you would need the author from HEAD~1
In my experience sending Slack messages to a private channel requires OAuth. I have only succeeded sending to private channels via slackSend() when Jenkins is added to Slack as a bot and invited to the channel.
Here's an example pipeline that works:
#!/usr/bin/env groovy
pipeline {
agent {
node {
label "master"
}
}
stages {
stage('Send Notification') {
steps {
script {
def color = "${params.MESSAGE_STATUS}" == "GOOD"? "good" : "warning"
slackSend(color: "${color}", message: "${params.MESSAGE}", channel: "${params.CHANNEL}")
}
}
}
}
parameters {
string(name: 'MESSAGE', defaultValue: 'Hello')
string(name: 'CHANNEL', defaultValue: '#test_private')
choice(name: 'MESSAGE_STATUS', choices: ['GOOD', 'WARNING'], description: '')
}
}
Sending via bots etc. hasn't been successful as Slack reports the channel as non-existant.

Trigger Input Step in Jenkins via HipChat

I can find tons of information in the internet about integrating HipChat in a scripted Jenkins pipeline. So that works fine for me. But how can I post a status message to HipChat that contains an element to trigger an action back in Jenkins?
Currently I have input steps in Jenkins to approve a deployment to the next stage, e.g. PROD.
I also send a HipChat message if approval is needed which contains a link to JENKINS. That looks like this:
hipchatSend color: "${color}", notify: true, room: "Jenkins Team FooBar", message: "${env.JOB_NAME}#${env.BUILD_NUMBER}: ${message}", textFormat: true
/************** PROD **************/
stage ('Approval for PROD') {
try {
timeout(time: approvalTime, unit: approvalTimeUnit) {
input 'Do you approve the deployment to PROD?'
}
} catch (Exception ex) {
finishBuild = true
}
}
// Stop build if flag was set
if (finishBuild)
return
How can I define actions in that hipChat message? Is there a way that I can approve the next build step within HipChat?
I have not found a tutorial or documentation on how to define other kinds of hipchat messages with this plugin.
I could send a POST request to JENKINS if the message would contain standard HTML. Any ideas on how to do that?
How would it work with cards?
Thanks in advance.

recipientProviders in jenkins pipeline are always empty

after finishing a job I want to send email notification. If the job is triggered manually at least RequesterRecipientProvider if filled with the user who triggered the build. I triggered from gitlab push webhook there is no email address configured in any of the recipientProviders.
emailext (
mimeType: 'text/html',
replyTo: '$DEFAULT_REPLYTO',
subject: subject,
body: details,
to: requester,
recipientProviders: [[$class: 'CulpritsRecipientProvider'],
[$class: 'RequesterRecipientProvider'],
[$class: 'DevelopersRecipientProvider'],
[$class: 'FailingTestSuspectsRecipientProvider' ],
[$class: 'FirstFailingBuildSuspectsRecipientProvider']
]
)
Any idea when those recipientProvider get filled? Where does email-ext get the recipient list from?
I've been banging my head with this for the last couple of days and i think i figured it out:
How it worked(for me):
First - In jenkins.co/configure check all the triggers for email ext plugin and fill in some emails in the default recipients input separated by a single space
Second- In the pipeline place the email ext code snippet just before closing the pipeline inside post brackets as follow
post{
always{
script{emailext(to: '$DEFAULT_RECIPIENTS', stuff....)}}}
This way I did not receive binding errors on build and the email was sent to the mailing list from default recipients, also the brackets nested in post{} seem to be the triggers checked at the previous step.

How to get culprits or committers inside a Jenkins workflow with one or more SCMs

Is it possible to access information about committers and/or culprits of a Jenkins workflow job when checking out from one or more SCMs (either via checkout() or other SCM steps like git/svn)?
The intention is to use that information to notify committers and/or culprits about the job status, for example in a mail step.
A small example of a workflow definition:
node {
// checkout from one or more SCMs, e.g.
git url: '<URL>'
checkout([$class:...])
...
// how can we know about committers or culprits at this point?
$committers = ??
// send a mail to committers or culprits
mail to: '$committers', subject: 'JENKINS', body: '<information about the job status>'
}
How could this be adapted to get a collection of the committers after running the SCM steps?
Edit:
I am currently working with Jenkins version 1.596.2 and Workflow: Aggregator version 1.6 and it seems this is an open issue in JENKINS-24141
This is now possible using the email-ext plugin.
def to = emailextrecipients([[$class: 'CulpritsRecipientProvider'],
[$class: 'DevelopersRecipientProvider'],
[$class: 'RequesterRecipientProvider']])
if (to != null && !to.isEmpty()) {
mail to: to, subject: "JENKINS", body: "See ${env.BUILD_URL}"
}
However, if you just want to send an email on failures, you may want to use Mailer (based on the email-ext pipeline examples):
step([$class: 'Mailer',
notifyEveryUnstableBuild: true,
recipients: emailextrecipients([[$class: 'CulpritsRecipientProvider'],
[$class: 'RequesterRecipientProvider']])])
Using groovy within a pipeline script:
#NonCPS // Necessary to allow .each to work.
def changelist() {
def changes = ""
currentBuild.changeSets.each { set ->
set.each { entry ->
changes += "${entry.commitId} by ${entry.author.fullName}\n"
}
}
changes
}
similar to the answer from #szym, but without the #NonCPS required:
def authors = currentBuild.changeSets.collectMany { it.toList().collect { it.author } }.unique()
As you found, pending JENKINS-24141 this is not supported. Changes to Jenkins core are required.
You can get the xml info for a job in which you will find the name of the person who committed the change along with the commit messages.
http://<Jenkins URL>:<Port Number>/job/<Jobname>/<BuildNumber>/api/xml?
Give this a go in your browser. Search for "user".
You can dump this information in a text file to process.
It seems that this feature was implemented inside the email-ext plugin but the author forgot to document the way we are supposed to use this.
Please check https://issues.jenkins-ci.org/browse/JENKINS-34763 -- and add a comment there, asking for an example. I already did.
You can fetch committers email :
committerEmail = sh (
script: 'git --no-pager show -s --format=\'%ae\'',
returnStdout: true
).trim()
and send:
emailext body: 'text you choose', subject: 'subject you choose', recipientProviders: [[$class: 'DevelopersRecipientProvider']], to: committerEmail
taken from : https://medium.com/#dilunika/find-the-git-commit-user-jenkins-pipeline-b6790613f8b5
In the emailext plugin you can provide culprits, developers, requestor etc in the recipientProviders directly.
emailext body: '',
recipientProviders: [culprits(),
developers(),
brokenBuildSuspects(),
brokenTestsSuspects(),
requestor()],
subject: ''
Description
Culprits: Sends email to the list of users who committed a change since the last non-broken build till now. This list at least always include people who made changes in this build, but if the previous build was a failure it also includes the culprit list from there.
Developers: Sends email to all the people who caused a change in the change set.
Broken Build suspects: Sends email to the list of users suspected of causing the build to begin failing.
Broken Test suspects: Sends email to the list of users suspected of causing a unit test to begin failing. This list includes committers and requestors of the build where the test began to fail, and those for any consecutive failed builds prior to the build in which the test began to fail.
Source: Jenkins Pipeline Syntax - Snippet Generator
If you want to notify the culprits who broke the build, You do not need to any checks, Use email plugin in jenkins. This plugin gives you option to send mails to commiter between past good build and current broken build.
If you are using "Editable email notifier plugin" You get option of send mail to culprit.
If you are using email plugin then you get the option "Send separate e-mails to individuals who broke the build".

Resources