Sending HTML report as an attachment to mail in jenkins - jenkins

I am new to Jenkins. As of now I have added email notification plugin. So once my test is completed now I am getting an email with Build log.
If I want to send Load runner HTML analysis report to mail in the same, what is the procedure?
Can anyone help me here ?
Thanks.

It's possible and it's pretty simple.
Download EmailExt plug-in (https://wiki.jenkins.io/display/JENKINS/Email-ext+plugin)
Then you can use the Pipeline Syntax to easily create it.
However, here's an example your can see as a reference to what you need.
emailext attachmentsPattern: '**/*.html', body: 'Body here', subject: 'Subject here', to: 'mail#gmail.com, mail2#gmail.com, mail3#gmail.com'
attachmentsPattern uses Ant File Syntax (http://ant.apache.org/manual/dirtasks.html)

I don't know if this will help, but i'm using https://wiki.jenkins.io/display/JENKINS/HTML+Publisher+Plugin
to generate html report from the jenkins workspace ( pwd() )
stage('sysdig report'){
publishHTML(target: [
allowMissing : true,
alwaysLinkToLastBuild: false,
keepAll : true,
reportDir : "${workspace}/",
reportFiles : "sysdig-report.html",
reportName : "sysdig-report"
])
You should be able to send the file after.

Related

Parsing console log from Jenkins and sending on email

I am trying to find solution for parsing logs from jenkins console and add matched logs into email body and send it via emailext.
I have following log lines in my console. I need to extract all matching lines and add in message body
OPERATION=backup|ENV_NAME=http://example.com:8091|EVENT=backup|START_TIME=2022-11-10 09:20:28.897461|END_TIME=2022-11-10 09:20:30.824839|RESULT=SUCCESS
I have similar log lines on console. all of them will have one common key-value that is "OPERATION=backup" and all the keys . I need to extract all lines having "OPERATION=backup|"
I have tried following but unable to parse it and add in message body .
success {
script {
def operations = manager.getLogMatcher ("(.*)OPERATION=backup(.*)")
}
emailext attachLog: false, mimeType: 'text/plain', subject: "DB backup for '${envNameAlias}' having build #${currentBuild.number}: ${currentBuild.currentResult}",
body: "Job completed..\nSee logs for more info:\n${env.BUILD_URL}/console",
to: 'abc.xyz#ey.org'
}
I am unclear about the steps forward. Please help with some inputs.
While going through belly of stackoverflow for solution, i found many solutions working with groovy post-build plugin, which is not installed in our organisation's jenkins.
solution :
tried following, works partially, i am getting almost whole log now in email then just few lines
success {
emailext attachLog: false, mimeType: 'text/plain', attachmentsPattern: '*', subject: "Couchbase export for build #${currentBuild.number}: ${currentBuild.currentResult}",
to: 'abc.xyz#ey.org',
body: """Job completed..\nSee logs for more info:\n ${env.BUILD_URL}/console \n \n \${BUILD_LOG_REGEX, regex="OPERATION=backup|", linesBefore=0, linesAfter=5, maxMatches=5, showTruncatedLines=false, escapeHtml=true} , regards Jenkins"""
}

How to debug Jenkin's `emailext` plugin?

emailext is by far the most popular email plugin for Jenkins and Jenkinsfiles.
How do you debug it?
It is failing to send the expected email with no error messages. The documentation for emailext doesn't indicate any kind of return value, callback, or any other way to get the status or result of the function call.
What methods exist (if any), in general, for debugging something like this?
(If you're curious about my specific use-case, I'll embed my code)
emailext(
to: "[REDACTED]#[REDACTED].com",
replyTo: 'no-reply#[REDACTED].com',
subject: '$DEFAULT_SUBJECT',
body: getEmailBody()
)
You can enable the debug mode of the plugin under Manage Jenkins > Configure System > Extended E-mail Notification then checkbox as in the following screenshot:
In the console output of your build, were you call emailext , you should then see more logs.

How to invoke email-ext plugin from Jenkins declarative script?

I am writing a simple Jenkins declarative script to run 'make' and send an email with the result (success/failure).
I can send a simple email using:
post {
success {
mail to:"myname#me.com", subject:"${currentBuild.fullDisplayName} - Failed!", body: "Success!"
}
failure {
mail to:"myname#me.com", subject:"${currentBuild.fullDisplayName} - Failed!", body: "Failure!"
}
}
The resulting email is rather simplistic.
How can I call the email-ext plugin from the script to send an old-style post-build email? (I guess this should use email-ext's groovy-text.template).
I would like to be able to access lists like CulpritsRecipientProvider and to include the tail of the console log.
You can use it in this way:
emailext (
subject: "STARTED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'",
body: """<p>STARTED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]':</p>
<p>Check console output at &QUOT;<a href='${env.BUILD_URL}'>${env.JOB_NAME} [${env.BUILD_NUMBER}]</a>&QUOT;</p>""",
recipientProviders: [[$class: 'DevelopersRecipientProvider']]
)
For more information you can check:
Sending Notifications in Pipeline
Email Extension Plugin

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".

Display HTML page inside mail body with Email-ext plugin in Jenkins

I am new to Jenkins and I want to know how it is possible to display the HTML report (not the HTML code) generated after a successful build inside a mail body (not as an attachment).
I want to know the exact steps I should follow and what should be the content of my possible jelly template.
Look deeper into the plugin documentations. No need for groovy here.
Just make sure Content Type is set to HTML and add the following to the body:
${FILE,path="my.html"}
This will place the my.html content in your email body (location of file is relative to job's workspace. I use it and it works well.
I hope this helps.
EDIT: Note that you must have the Jenkins version 1.532.1 (or higher) to support this feature with the email-ext plugin.
Besides reading the file with body: ${FILE,path="index.html"}, you need to set the proper content type, either globally or explicitly for one execution, with mimeType: 'text/html.
emailext subject: '$DEFAULT_SUBJECT',
body: '${FILE,path="index.html"}',
recipientProviders: [
[$class: 'CulpritsRecipientProvider'],
[$class: 'DevelopersRecipientProvider'],
[$class: 'RequesterRecipientProvider']
],
replyTo: '$DEFAULT_REPLYTO',
to: '$DEFAULT_RECIPIENTS',
mimeType: 'text/html'
It worked for me with Jenkins 1.558
${FILE,path="target/failsafe-reports/emailable-report.html"}
It should be something like this:
Navigation:
Configure -> Editable Email Notification
Default Content:
${FILE,path="path/result.html"}
If you use a custom path
I had a complication trying to achieve this result because my path was dynamically changing and I had to use a variable inside a FILE variable. So when I tried any of the following
body: '${FILE,path=${report}}'
body: "${FILE,path=${report}}"
body: '''${FILE,path=${report}}'''
and many more, it didn't work. On the other hand I couldn't read the file with groovy because of Jenkins restrictions
My workaround was to read the html directly with shell like so
html_body = sh(script: "cat ${report}", returnStdout: true).trim()
and then just send the email
emailext replyTo: '$DEFAULT_REPLYTO',
subject: "subject",
to: EMAIL,
mimeType: 'text/html',
body: html_body
where ${report} was a path to html file like /var/jenkins/workspace_318/report.html
You just need to assign the link to the environment variable and then you can use that variable to print in the email using ${ENV, var=ENV_VARIABLE}.
You can use Editable Email Notification post build action to send html content as part of mail body.
Copy html content in Default Content and select Content Type as HTML (text/html), as in below image:

Resources