Showing posts with label Jenkins. Show all posts
Showing posts with label Jenkins. Show all posts

Tuesday, 26 December 2017

TechTip - How to embed html report within the Jenkins email notifications?

If you would like to send html report through Jenkins email notifications and looking for how to embed html report within the Jenkins email notifications, you can follow below steps:

Prerequisite

Ensure that your Jenkins has email-ext-plugin installed. If not, refer this and install it first.

Steps

Follow below steps to embed html file in email content:
  1. Go to your jenkins job and click on Configure.
  2. Go to Post Build Actions and then select Editable Email Notifications
  3. Select Content Type as HTML(text/plain)
  4. In the default content section replace $DEFAULT_CONTENT with following
           ${FILE,path=”relative path to html file”}

Example

For example, below is the absolute path for your html file. So you just need to pick bold marked as relative path and mention in path.

/app/jenkins/jobs/myjob/workspace/my-maven-module/target/site/surefire-report.html


${FILE,path="my-maven-module/target/site/surefire-report.html”}


This will place the surefire-report.html content in your email body.


Hope this tip is helpful for you.




Saturday, 8 August 2015

Deployment Automation using Jenkins API and Shell Script

If you are using Jenkins as continuous integration system and looking forward to automate deployment activities using Jenkins API and Shell script, this blog may help you out. 

What could be the deployment activities?
In my project, I experienced below manual activities those are required as part of deployment. 
  1. Send Notification before Deployment: Before triggering deployment, developer has to notify team that he is going to trigger deployment. Each developer has to wait for SVN check-ins so that new Jenkins build is not triggered due to their check-ins.
  2. Connect to Remote Linux Boxes: Login to Linux boxes through SSH client and trigger the deployment through shell script which used to deploy application into WebSphere. The responsibility of this script is to download EAR from Jenkins and trigger deployment through WebSphere commands.
  3. Apply DB Changes: Execute database changes into common dev environment's DB schema.
  4. Deploy UI Static Contents: After EAR deployment, UI contents need to be deployed into Node.js HTTP server.
  5. Application Health Check: Once, deployment is done then developer has to verify whether applications are deployed successfully and these are working fine.
  6. Send Notification after Deployment: Finally, notify the team that deployment is done and now common development environment is up and running.

All these manual steps are time consuming and impact development cost up to some extent. Why can't all these steps can be automated? Is there any way where you can automate these activities through script? I know there are different tools in market for automatic deployment. But if you don't want to use other tools and looking for simple automation script, this blog can help you out for sure. 

Deployment Activity Flow Diagram
Before automating any steps you need to understand what are the steps and what should be the flow. Let's see the flow of deployment activities first and then try to automate through different unix commands in script. 



How to achieve it?
Unix commands and shell script is one of the best option to automate all aforementioned activities. I explored Jenkins API and Jenkins-cli library  which can be accessed through unix command.

1. Send notification before deployment

First declare below variables in your shell script:
senderEmailId="xyz@xyz.com"
recipients="abc@xyz.com"
Subject= "Deployment is started"
body="<html> <head> <title>HTML E-mail</title> </head> <body>Deployment is started<body>
</head></html>"

Use below command to send mail notification from your script:
( echo "From: $senderEmailId"; echo "To: $recipients"; echo "Subject: $subject "; echo "Content-Type: text/html"; echo "MIME-Version: 1.0"; echo ""; echo "$body";)| /usr/sbin/sendmail -t
2. Check whether current build is failed or success, if failed send deploy failed notification

First declare below variables in your shell script:
user="jenkins-user"
pass="jenkins-pass"
IP="jenkins-ip"
port="jenkins-port"
job="jenkins-job"
subject= "Build is in failed state"  
Use below command to check whether build is failed:
lastBuildNumber=$(curl -s  --insecure       https://$user:$pass@$IP:$port/jenkins/job/$job/lastBuild/buildNumber)
lastSuccessfullBuild=$(curl -s  --insecure https://$user:$pass@$IP:$port/jenkins/job/$job/lastSuccessfulBuild/buildNumber)

#Check if build is stable
if [ "$lastBuildNumber" == "$lastSuccessfullBuild" ]; then
        echo "Latest build is stable. Build $lastBuildNumber can be deployed."
else
       failedBuildLogs=$(curl -s --insecure https://$user:$pass@$IP:$port/jenkins/job/$job/$lastBuildNumber/consoleText | tail -n 100)
      ( echo "From: $senderEmailId"; echo "To: $recipients"; echo "Subject: $subject "; echo "Content-Type: text/html"; echo "MIME-Version: 1.0"; echo ""; echo "$body";)| /usr/sbin/sendmail -t
      echo "Exit from script"
      exit
fi
3. Check whether current build is not in-progress, if so send deploy failed notification

Use below commands to check whether build is in progress :
lastStableBuild=$(curl -s --insecure https://$user:$pass@$IP:$port/jenkins/job/$job/lastStableBuild/buildNumber)
if [ "$lastBuildNumber" == "$lastStableBuild" ]; then
        echo "Latest build is stable. Build $lastBuildNumber can be deployed."
else
      ( echo "From: $senderEmailId"; echo "To: $recipients"; echo "Subject: $subject "; echo "Content-Type: text/html"; echo "MIME-Version: 1.0"; echo ""; echo "$body";)| /usr/sbin/sendmail -t
      echo "Exit from script"
      exit
fi

4. If build is stable then disable it

Before starting deployment its better to disable build so that other check-in during deployment may not trigger another build. To disable build use below command.
curl -X POST --insecure https://$user:$pass@$IP:$port/jenkins/job/$job/disable

5. Execute your deployment script 

At this point, execute your deployment script.

6. After deployment enable the build
curl -X POST --insecure https://$user:$pass@$IP:$port/jenkins/job/$job/enable
7. Perform application health check

After deployment is done, it's better to check whether all applications are accessible. How you can check it automatically? In our application we used log4j configuration that facilitates changing log level dynamically. I used the same log4j URLs to perform application health check. Use below commands for application health check.

healthCheckMailContentTableGrid="<h3>Applications Health Check</h3><table><tr><th>Application</th><th>Instance</th><th>Status</tr>"
declare -a appArr=("app1-context" "app2-context")
declare -a instanceArr=("127.0.0.1:9080" "127.0.0.1:9082")
log4jPackage=com.xxx
isAnyApplicationNotWorking=1
for i in "${appArr[@]}"
do
   echo "Checking health of $i application"
   for instance in "${instanceArr[@]}"
   do
              #Application specific log4j URL 
     healthCheckUrl="http://$instance/$i/Log4JControl/"
     healthCheckStr=$(curl -s --insecure --connect-timeout 5  $healthCheckUrl)
               # If log4jPackage is found in the returned string, consider that app is working
     found=$(echo $healthCheckStr | grep -c $log4jPackage)
     healthCheckHtml="<tr><td>$i</td><td>$instance</td>"
     if [ $found -eq 1 ]; then
          echo "---> App $i is accessible [ $instance ]"

          healthCheckMailContentTableGrid=$healthCheckMailContentTableGrid$healthCheckHtml"<td bgcolor=\"green\">Accessible</td></tr>"
     else
          isAnyApplicationNotWorking=0
          echo "---> App $i is not accessible [ $instance ]"

          healthCheckMailContentTableGrid=$healthCheckMailContentTableGrid$healthCheckHtml"<td bgcolor=\"red\">Not Accessible</td></tr>"
     fi
     echo $found
    done
done
8. Prepare build summary for notification and send successful deployment notification.

In this step you can collect all information like deployed build number, application health check details, changes list which is made in last deployed build and current deployed build etc.
lastBuildNumber=$(curl -s  --insecure  https://$user:$pass@$IP:$port/jenkins/job/$job/lastBuild/buildNumber)
jreLocation=/opt/java/bin 
latestBuildChanges=$($jreLocation/java -jar jenkins-cli.jar -noCertificateCheck -s https://@$IP:$port/jenkins  list-changes  $job $lastBuildNumber --username $user --password $pass) 
lastDeployedBuildNumber ="Set your last deployed build number"
changesBetweenLastAndLatestDeployedBuild=$($jreLocation/java -jar jenkins-cli.jar -noCertificateCheck -s https://@$IP:$port/jenkins  list-changes  $job $lastBuildNumber-$lastDeployedBuildNumber --username $user --password $pass)
At last consolidate deployment summary and send successful deployment notification along with detail.



Saturday, 14 December 2013

Setup Jenkins Continuous and Automatic Build System

Jenkins is an open source tool which provides continuous integration services for software development. If you want to get more detail about Jenkins and it's history I would suggest refer this link. This post will help you installing and configuring Jenkins and creating jobs to trigger maven builds. Setting up Jenkins is not a rocket science indeed. In this post, I would like to concise the installation and configuration steps.


Installing Jenkins
Though, there are different ways to install Jenkins. But, in this post I will be describing Jenkins installation with Apache Tomcat server. Hence, please make sure that you have Apache Tomcat.   
  1. Download Jenkins war file from here and copy war into tomcat's 'webapp' folder
  2. Start the tomcat server and access Jenkins

Jenkins installation is done. Wow, so easy. Isn't it?

Configuring Jenkins
Now you have Jenkins running with you. It's time to configure the project specific environment for continuous and automatic build. This section describes about JDK, Maven and Mail Notification configuration.

Go to 'Manage Jenkins

 

Go to 'Manage Jenkins > Configure System'




Creating Job for Automatic and Continuous Build
So far you installed and configured  the Jenkins. It's time to create new job. Before creating new job ensure that your project is a maven project. Now, go to 'New Job' and fill the required information. believe, below screen shot tells everything which is required to configure a job. You just need to configure below points at minimum:
  • Source Code Management
  • Build Triggers
  • Build
  • Notifications





Once you save the job you will see below screen


Now click on 'Build Now' and see the 'Build History'. You will get new entry in 'Build History'. To see the build logs just hover the mouse on this build and click on 'Console Output', you can see the build logs.



Congratulations! you are done with setting up continuous build system.If you want to see that how effectively it works, just check-in any file in your project and see whether your build is triggered automatically. In case, build is failed with latest checked-in changes you must get a notification mail saying build is failed.

Last but not least, you should agree with my point 'Setting up Jenkins is not a rocket science indeed'. Shouldn't you? :) :) :)

Saturday, 30 November 2013

Hudson Plugin for Eclipse

If you are using Hudson as continuous integration server and you might feel lazy about accessing Hudson explicitly to check the build status or checking Hudson build status mails, there is an option to monitor Hudson build and perform build activities in Eclipse IDE itself. This post describes about installing, configuring and using the Hudson in Eclipse IDE.

Installing Hudson Plugin in Eclipse
Use below URL To install the Hudson Eclipse plugin using Eclipse Update Manager:

In case you face issue while installing plugin using update manager you can directly drop dk.contix.eclipse.hudson_x.x.x.jar  in Eclipse's plugins directory and restart IDE.

Configuring Hudson 
Once the installation is done, configure the Hudson URL from Preferences > Hudson to connect to Hudson server. Also remember to Check URL whether URL is valid or not. Your Hudson server must be running at this point of time.


How to Use Hudson in Eclipse?
In eclipse, go to Windows > Show View > Hudson. You will see below tab is added in your Eclipse. Also, When the plugin is running, a health icon is displayed at the bottom of the Eclipse window. The icon is red on build failure and green on success.  Please note that due to limitations in Eclipse, the Hudson view must be active before the icon is displayed.


In case build is failed, you will get below pop-up in your eclipse IDE. 


You can also perform below activities using this Eclipse Hudson plugin.For this, select any project listed in Hudson tab and right click.
  1. Schedule New Build
  2. View Console Output
  3. Open Hudson in Browser


If you want to  access the Hudson admin console in your Eclipse,  go to 'Hudson' tab and double click on your project.


Limitations 
If your Hudson server requires authentication and authorization for access, then you can not see the list of jobs in Eclipse. Because Eclipse Hudson plugin does not facilitates interface to provide Hudson web credentials. To overcome this limitation, you have to give read permission to Anonymous user for jobs in Hudson which need to be displayed in Eclipse. 

Common Issues
  •  Issue in configuring Hudson base URL which is SSL enabled
Solution: This issue is due to missing required certificates. Refer below links to generate the certificate. Once the certificate is generated you can copy those into $JAVA_HOME/lib/security for the JRE that eclipse is using for its run time. It will trust that cert and then you can access configured HTTPS URL successfully.

  • Once your certificate issue is resolved then you may face below issue
             java.security.cert.CertificateException: No subject alternative names present

            Solution: Configure HTTPS URL using DNS rather giving IP address.
             For example: Use this https://mybox.com/hudson instead of  https://XX.XX.XX.XX/hudson 
  • While refreshing build status you get below pop-up 

            Solution: Ensure that your job's name in Hudson does not contain white spaces.

References
Below are the references for more detail about Hudson Eclipse plugin.