Jenkins - sending email depends on console output - jenkins

I have an app in Java and I'd like to run the app with Jenkins.
The app could log info "[Email] example log" or throw a specific exception in some cases.
Now I'd like to use Jenkins to send e-mails after build when Jenkins see in its Console output:
log: [Email] .....
specific exception has been throw
I configured Editable Email Notification and Emailext (all email parameters like smtp etc are done) and I can add it to Post-build Action
[1]: https://i.stack.imgur.com/8psbf.png
but I never used Jenkins before and I don't know which trigger should I choose in that case and where/how to write 'if code' to do what I want.
EDIT: I should probably write some Pre-send Script?

If you would like to send email, then you can directly add it in the pipeline.
Configure System:
Go to Manage Jenkins-> Configure System. Here scroll down to the email notification section. If you are using Gmail then type smtp.gmail.com for the SMTP server. Click on Advanced and select Use SMTP authentication. Enter your Gmail username and password. Select the Use SSL option and enter the port number as 465. Click on Apply and then Save.
Create Jenkins Pipeline Job:
pipeline {
agent any
stages {
stage("Send Email")
{
steps {
emailext body: 'your body', subject: 'your sububject', to: 'abc#gmail.co,'
}
}
}
}
Above method was an example to show you how you can send email via pipeline.
Execute your App and then send Email:
pipeline {
agent any
stages {
stage("App execution")
{
steps {
// Execute your app
bat label: 'Execute your app', script:"yourapp.bat >log.txt "
}
}
stage("Send Email")
{
steps {
emailext body: 'your body', subject: 'your sububject', to: 'abc#gmail.co,'
}
}
}
}
Send email based on conditions
pipeline {
agent any
stages {
stage("App execution")
{
steps {
// Execute your app
bat label: 'Execute your app', script:"yourapp.bat >log.txt "
}
}
stage("Send Email")
{
steps {
// You can add condition based on your log file in previous step :
// Example : please change below code as per your logic
// if log contains "Email" then only send email
if(log.contains(" Email:")){
emailext body: 'your body', subject: 'your subject', to: 'abc#gmail.co,'
}
}
}
}
}

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}

How do I know which stage of jenkins pipeline has failed

In my Jenkins pipelines I generally use post declarative function to send me an email incase the pipeline has failed.
A simple syntax of the post function is as under:
post {
failure {
mail to: 'team#example.com',
subject: "Failed Pipeline: ${currentBuild.fullDisplayName}",
body: "Something is wrong with ${env.BUILD_URL}"
}
}
In the above email, I also want to mention which stage (lets say the pipeline has 5 to 6 stages) of the pipeline has failed. How can I do that? Any help is much appreciated.
An extension to the above requirement will be to provide the user with the actual error log (of the stage that has failed) also as a part of the failure notification email.
Idea is, when a user receives a failure notification from jenkins, he should know which stage of the pipeline has failed along with the error log.
Thanks in advance.
There is a variable called env.STAGE_NAME which you can use. However, in your case you will probably need to store the stage name in a different variable, because when you get the env.STAGE_NAME in a post stage the result will be Declarative: Post Actions. Instead, you will need to store the stage name in a variable in all stages. So once a stage fails - Jenkins will not continue with the next stages and therefore you will have the "failed" stage name.
Here's an example:
def FAILED_STAGE
pipeline {
agent { label "master" }
stages {
stage("Stage 1") {
steps {
script {
FAILED_STAGE=env.STAGE_NAME
echo "stage 1"
}
}
}
stage("Stage 2") {
steps {
script {
FAILED_STAGE=env.STAGE_NAME
echo "stage 2"
error "failed for some reason."
}
}
}
stage("Stage 3") {
steps {
script {
FAILED_STAGE=env.STAGE_NAME
echo "stage 3"
}
}
}
}
post {
failure {
echo "Failed stage name: ${FAILED_STAGE}"
}
}
}
There might be a better way to do it, but I haven't found it so far.
Regarding the logs - As of JENKINS-40526 you could possibly use the API and get the log file from there, but I am not sure you can get the parameters you need from within the pipeline. The other solution would be to use emailext and email the entire build log file:
emailext attachLog: true, body: '', compressLog: true, subject: 'Build failed.', to: 'somebody#somewhere.com'

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.

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

Pipeline Input step, on abort send email

I haven't seen a way to capture an abort on the input option in the pipeline
Or a post pipeline step to send an email. I'm assuming this requires some groovy.
I assume that you have a jenkinsfile or a pipeline script with an input step in it.
try {
input message: "Send deployment request?"
} catch (err) {
mail body: "Not a deployment request", to: "support#email.dot", from: "me#me.com", subject:"testando"
}

Resources