dmesg
dmesg

Reputation: 101

Initiate an email based on script output or console output in Jenkins

I have a script which basically fetches the http response codes. I want to trigger an email for response code anything apart from 200. I do not want to trigger mail using script. Is there any way to send a mail in post build actions ?

Kindly assist.

#!/bin/bash
date
if [ $# -eq 0 ]; then
   cat /home/ubuntu/check_kibana/lists.txt | while read output
do
    RESP=$(curl -sL $output -w "%{http_code} \n" -o /dev/null)
    if [ $RESP -eq 200 ]; then
        echo "ResponseCode: $RESP, Service is active."
    else
        echo "ResponseCode: $RESP, $output is not active."
        echo "ResponseCode: $RESP for $output. Please check as the service may be down or not listening to the designated port." | mail -s "Error triggered for unavailable kibana service" [email protected]
    fi
done
fi

Upvotes: 2

Views: 896

Answers (2)

Mike
Mike

Reputation: 615

If you are running this as a build step then you need to add exit 1; in the else part of the response code check. This will mark the build step as a failure and then you can set up an email trigger using "Email Notification" as a post-build step. In case, If you want to have personalized email then you can use "Editable Email Notification" plugin.

So, your script should be something like this

#!/bin/bash
date
if [ $# -eq 0 ]; then
   cat /home/ubuntu/check_kibana/lists.txt | while read output
do
    RESP=$(curl -sL $output -w "%{http_code} \n" -o /dev/null)
    if [ $RESP -eq 200 ]; then
        echo "ResponseCode: $RESP, Service is active."
    else
        exit 1; # Any exit code except 0 will mark the build step as the failure 
        echo "ResponseCode: $RESP, $output is not active."
        echo "ResponseCode: $RESP for $output. Please check as the service may be down or not listening to the designated port." | mail -s "Error triggered for unavailable kibana service" [email protected]
    fi
done
fi

Upvotes: 1

dmesg
dmesg

Reputation: 101

To fix the above issue, we need to know that Jenkins will trigger the email notification only if the build fails or changes from failure to success. (depends on how you want to trigger an email via Jenkins).

I have found a way to solve the above issue. Instead of shell script, python would be right choice for me me as it is very flexible to play around with the various libraries and variables. So, those who want to trigger an email based on the loop conditions in the script, go with python or any OOP languages.

Shell script will only run the script and sets the build status. If I am wrong, I'd be happy receive the suggestions.

Upvotes: 0

Related Questions