0% found this document useful (0 votes)
7 views15 pages

Section10 Jenkins&Maven

This document provides a comprehensive guide on using Jenkins and Maven for Continuous Integration (CI) in Java projects. It covers the integration of Jenkins with Maven and Git, installation of necessary plugins, cloning repositories, building JAR files, executing unit tests, deploying applications, and visualizing test results. Key takeaways emphasize the automation of builds, testing, and deployment processes to enhance code quality and streamline development workflows.

Uploaded by

Sachin Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views15 pages

Section10 Jenkins&Maven

This document provides a comprehensive guide on using Jenkins and Maven for Continuous Integration (CI) in Java projects. It covers the integration of Jenkins with Maven and Git, installation of necessary plugins, cloning repositories, building JAR files, executing unit tests, deploying applications, and visualizing test results. Key takeaways emphasize the automation of builds, testing, and deployment processes to enhance code quality and streamline development workflows.

Uploaded by

Sachin Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

1.

Introduction to Jenkins & Maven


Objectives of the Section:
• Understanding Maven, a powerful tool for building Java applications.
• Learning how Maven and Jenkins work together.
• Creating an entire project using Maven.
• Building and testing Java applications with Maven.
• Introduction to Continuous Integration (CI) and how Jenkins automates builds and testing.
• Using Git, Maven, and Jenkins together in a real-world CI/CD environment.

What is Maven?
• Maven is a build automation tool for Java projects.
• Helps in compiling, testing, packaging, and managing dependencies of Java applications.
• Simplifies project management with a standardized project structure.

Maven & Jenkins Integration:


• Jenkins is an automation server used for Continuous Integration (CI).
• Maven and Jenkins work well together to automate the build, test, and deployment
process.
• This section will focus on integrating Jenkins, Git, and Maven to simulate a real-world
CI/CD pipeline.

Understanding Continuous Integration (CI) with Maven & Jenkins


• CI ensures that code changes from multiple developers are integrated frequently into a
shared repository (e.g., Git).
• Workflow Example:
1. Developers push changes to a Git repository.
2. Jenkins automatically detects the changes and triggers a Jenkins job.
3. Jenkins:
• Downloads the latest code from Git.
• Builds a JAR file using Maven.
• Executes unit tests to verify the functionality.
• Deploys the JAR if the tests pass.
4. The process ensures that the application remains functional and stable after every
change.
Key Takeaways:
• Maven helps in building and managing Java applications efficiently.
• Jenkins automates the CI process by detecting changes, building, testing, and deploying
the application.
• CI improves code quality and reduces integration issues in a team development
environment.

2. Installing the Maven Plugin in Jenkins


Objective:
• Learn how to install the Maven plugin in Jenkins for integrating Maven-based builds.

Steps to Install the Maven Plugin in Jenkins:


1. Access Jenkins Plugin Manager:
• Navigate to Manage Jenkins → Manage Plugins.
2. Search for the Maven Plugin:
• Go to the Available Plugins tab.
• Use the search bar and type "Maven" to filter results.
3. Select and Install the Plugin:
• Locate Maven Integration Plugin in the search results.
• Click on the plugin and select Install without restart.
• Wait for the installation to complete.
• After installation, click Restart Jenkins when installation is complete (optional but
recommended).
4. Verify the Installation:
• After Jenkins restarts, navigate back to Manage Jenkins → Manage Plugins.
• Go to the Installed tab and filter using the keyword "Maven".
• You should see both:
• Maven Plugin
• Maven Integration Plugin

Key Takeaways:
• The Maven Integration Plugin allows Jenkins to work with Maven-based projects.
• Installation is done via Manage Plugins in Jenkins.
• Restarting Jenkins after installation ensures the plugin is loaded correctly.
• Validation can be done by checking the Installed Plugins tab.
3. Installing the Git Plugin in Jenkins
Objective:
• Learn how to install the Git plugin in Jenkins to enable Git integration for source code
management.

Steps to Install the Git Plugin in Jenkins:


1. Access Jenkins Plugin Manager:
• Navigate to Manage Jenkins → Manage Plugins.
2. Search for the Git Plugin:
• Go to the Available Plugins tab.
• Use the search bar and type "Git" to filter results.
3. Select and Install the Plugin:
• Locate Git Plugin in the search results.
• Click on the plugin and select Install without restart.
• Wait for the installation to complete.
• (Optional) Click Restart Jenkins when installation is complete to ensure proper
functionality.
4. Verify the Installation:
• After Jenkins restarts, navigate back to Manage Jenkins → Manage Plugins.
• Go to the Installed tab and filter using the keyword "Git".
• You should see the Git Plugin listed, confirming a successful installation.

Key Takeaways:
• The Git Plugin is required for integrating Git repositories with Jenkins.
• Installation follows the same process as other Jenkins plugins.
• Restarting Jenkins ensures the plugin loads correctly.
• Verification is done via the Installed Plugins tab in Jenkins.

4. Cloning a Git/GitHub Repository from


Jenkins
Objective:
• Learn how to clone a Git repository using Jenkins.
• Understand Source Code Management (SCM) and Jenkins workspaces.
Steps to Clone a Git Repository in Jenkins
1. Find a Sample Maven Repository
• Open Google and search for "sample Maven app".
• Select a GitHub repository containing Maven project files (e.g., pom.xml).

2. Create a New Jenkins Job


1. Go to Jenkins Dashboard → Click on New Item.
2. Enter a job name (e.g., maven-job).
3. Select Freestyle project and click OK.

3. Configure Source Code Management (SCM)


• SCM stands for Source Code Management, which refers to the location of the project's
source code.
• Jenkins Git plugin allows integration with both GitHub and GitLab.
Steps to configure SCM in Jenkins:
1. Scroll down to Source Code Management.
2. Select Git.
3. Copy the GitHub repository URL and paste it into the Repository URL field.
4. (Optional) Click Advanced to specify a different branch (default is master).
5. No authentication is required for public repositories.

4. Save and Build the Job


• Click Save to apply the changes.
• Click Build Now to start cloning the repository.
How does Jenkins handle this?
• The Git plugin fetches the code from the specified repository.
• The console output will display the cloning process and confirm if it was successful.

5. Understanding Jenkins Workspace


• Workspace is the directory where Jenkins stores files for each job.
• Every job has its own workspace where cloning, building, and testing occur.
To find the workspace manually:
1. Open a terminal and access the Jenkins container:
docker exec -ti jenkins bash
2. Navigate to Jenkins home directory:
cd /var/jenkins_home/workspace/

3. List all jobs:


ls -l

4. Navigate to the workspace of the specific job (e.g., maven-job):


cd maven-job
ls -l

5. Verify that the cloned repository matches the original GitHub repo structure.

Key Takeaways:
✅ SCM (Source Code Management) helps Jenkins fetch the latest code from repositories.
✅ Jenkins stores project files in a workspace specific to each job.
✅ The Git plugin allows seamless integration with GitHub/GitLab.
✅ Users can manually verify cloned files within the Jenkins workspace directory.

5. Building a JAR Using Maven in Jenkins


Objective:
• Learn how to configure Maven in Jenkins.
• Understand the process of building a JAR file using Maven.
• Locate and verify the generated artifact (JAR file) in the Jenkins workspace.

1. Configure Maven in Jenkins


Before we can build a JAR, we need to install and configure Maven in Jenkins.

Steps to Configure Maven:


1. Go to Jenkins Dashboard → Click on Manage Jenkins.
2. Click Global Tool Configuration.
3. Find the Maven section and click Add Maven.
4. Enter a name for the installation (e.g., jenkins-maven).
5. Select the latest Maven version.
6. Click Save.
2. Configure the Maven Job in Jenkins
Now, let’s modify the maven-job to build the JAR file.

Steps to Configure the Job:


1. Go to Jenkins Dashboard → Select maven-job.
2. Click Configure.
3. Scroll down to the Build section.
4. Click Add build step → Select Invoke top-level Maven targets.
5. Under Maven Version, select jenkins-maven (the one configured earlier).

6. Under Goals, enter:


clean package -DskipTests

• clean → Cleans old build files.


• package → Compiles the code and creates a JAR.
• -DskipTests → Skips unit tests during the build process.
7. Click Save.

3. Run the Build and Verify Output


Steps to Build the JAR:
1. Click Build Now.
2. Go to Build History → Click the latest build.
3. Open Console Output to monitor the build process.

What Happens During the Build?


• Jenkins first pulls the latest code from GitHub.
• If this is the first build, Jenkins downloads the specified Maven version (one-time
process).
• Maven processes the pom.xml file and generates a JAR file.

4. Locate the Built JAR File


The JAR file is stored in the Jenkins workspace.

Steps to Find the JAR:


1. Access the Jenkins server:
docker exec -ti jenkins bash
2. Navigate to the workspace directory:
cd /var/jenkins_home/workspace/maven-job/target

3. List the files to verify the JAR:


ls -l

4. You should see the JAR file generated in the target/ directory.

5. Key Takeaways
✅ Maven Integration → Configured in Jenkins under Global Tool Configuration.
✅ Maven Job → Defined in Jenkins to automatically fetch and build the latest code.
✅ Artifacts → The resulting JAR file is stored in the target/ directory in the workspace.
✅ Continuous Integration (CI) Flow:
• Pull latest code
• Build the JAR
• Store it in the workspace

6. Executing Unit Tests in Jenkins Using


Maven
Objective:
• Learn how to configure Maven to run unit tests in Jenkins.
• Fix environment variable issues that may cause test failures.
• Validate successful test execution in the build pipeline.

1. Understanding the Continuous Integration Flow


At this point, we have a Jenkins job that:
✅ Clones the GitHub repository to fetch the latest code.
✅ Builds a JAR file using Maven.
✅ Now, we will execute unit tests to validate the build.

2. Configure Maven to Run Tests in Jenkins


Steps to Modify the Maven Job:
1. Go to Jenkins Dashboard → Select maven-job.
2. Click Configure.
3. Scroll down to the Build section.
4. Click Add build step → Select Invoke top-level Maven targets.
5. Under Maven Version, select jenkins-maven (configured earlier).
6. Under Goals, enter:
test

• test → Runs all unit tests defined in the project.


7. Click Save.

3. Run the Build and Analyze Console Output


Steps to Run the Build:
1. Click Build Now.
2. Go to Build History → Select the latest build.
3. Open Console Output to monitor execution.

What Happens During the Build?


1. Git Clone → Pulls the latest code from GitHub.
2. Maven Build → Compiles and packages the code into a JAR.
3. Unit Tests Execution → Runs the tests found in the src/test/ directory.

4. Fixing Common Errors (Environment Variable Issue)


Issue:
• Some versions of Debian-based systems cause test failures due to a missing Java options
environment variable.
• The error message might look like:
java.lang.RuntimeException: No X11 DISPLAY variable was set

Solution:
1. Go to Jenkins Dashboard → Click Manage Jenkins.
2. Click Configure System.
3. Find Global Environment Variables → Click Add.
4. Enter:
• Name: JAVA_TOOL_OPTIONS
• Value: -Djava.awt.headless=true
5. Click Save.
5. Re-run the Build to Validate Fix
Steps to Verify Fix:
1. Click Build Now again.
2. Check the Console Output.
3. You should see:
Tests run: 2, Failures: 0

4. If you see Failures: 0, it means all tests passed successfully. 🎉

6. Key Takeaways
✅ Unit Testing Integrated → Maven test command is added to Jenkins job.
✅ Error Handling → Fixed environment variable issue for Debian-based systems.
✅ CI Workflow Extended → Now includes code validation through unit tests.
This is the core of Continuous Integration (CI) – ensuring the latest code is compiled, packaged,
and validated automatically. 🚀

7. Deploying Your JAR Locally Using Jenkins


Objective:
• Learn how to deploy a JAR file after successful testing.
• Use a shell build step in Jenkins to automate deployment.
• Verify that the JAR executes correctly.

1. Continuous Integration Workflow Recap


At this point, your Jenkins pipeline follows these steps:
✅ Clone the GitHub repository (fetch latest code).
✅ Build the JAR file using Maven.
✅ Run unit tests to ensure application correctness.
✅ Now, we will deploy the JAR only if all tests pass.

2. Locating the Built JAR File


Where is the JAR Stored?
• When Maven builds the project, the JAR is saved in the target/ directory inside the Jenkins
workspace.
• You can find it in the Console Output after a successful build:
[INFO] Building jar: /var/jenkins_home/workspace/maven-job/target/my-app-
1.0.jar

• The full path is:


/var/jenkins_home/workspace/maven-job/target/my-app-1.0.jar

3. Add a Shell Script to Deploy the JAR


Steps to Modify the Jenkins Job:
1. Go to Jenkins Dashboard → Select maven-job.
2. Click Configure.
3. Scroll down to Build → Click Add build step.
4. Select Execute Shell.
5. Inside the shell script box, enter:
echo "************************************"
echo "Deploying JAR..."
echo "************************************"
java -jar /var/jenkins_home/workspace/maven-job/target/my-app-1.0.jar

6. Click Save.

4. Run the Build and Verify Deployment


Steps to Execute the Build:
1. Click Build Now.
2. Select the latest build from Build History.
3. Click Console Output to monitor execution.

Expected Output in Console:


************************************
Deploying JAR...
************************************
Hello, World!

• If your JAR contains a simple application that prints "Hello, World!", you should see
this message.
• This confirms that the JAR is executing correctly.

5. Running the JAR Inside the Jenkins Container


Verify Deployment Inside the Jenkins Server:
• SSH into the Jenkins container:
docker exec -it jenkins_container_name bash

• Run the JAR manually:


java -jar /var/jenkins_home/workspace/maven-job/target/my-app-1.0.jar

• You should see the same "Hello, World!" output.

6. Key Takeaways
✅ Automated Deployment → Jenkins now builds and runs your JAR.
✅ Error Prevention → JAR is deployed only if all tests pass.
✅ Verifying Deployment → Output confirms JAR execution inside Jenkins.

8. Visualizing Test Results with a Graph in


Jenkins
Objective:
• Learn how to generate a test report using Jenkins.
• Use JUnit test results to create a graphical trend.

1. Maven Generates Test Reports Automatically


Where is the Test Report Located?
• When you run mvn test, Maven generates a JUnit XML report.
• This report is stored inside the target/surefire-reports/ directory.
• Inside Jenkins, the full path to this report is:
/var/jenkins_home/workspace/maven-job/target/surefire-reports

• You can verify this inside your Jenkins container by running:


ls /var/jenkins_home/workspace/maven-job/target/surefire-reports/*.xml

2. Configure Jenkins to Publish JUnit Reports


Steps to Enable Graphical Test Reports:
1. Go to Jenkins Dashboard → Select maven-job.
2. Click Configure.
3. Scroll down to Post-Build Actions.
4. Click Add Post-Build Action → Select Publish JUnit Test Result Report.
5. In the "Test Report XMLs" field, enter:
target/surefire-reports/*.xml

6. Click Save.

3. Run the Jenkins Job Multiple Times


Why Multiple Runs?
• The test trend graph requires multiple builds to display meaningful data.
• Run the job at least 5 times to populate the graph.

How to Trigger Multiple Builds?


• Click Build Now 5 times.
• After each run, check Console Output to verify test execution.

4. Viewing the Test Result Trend Graph


Steps to See the Graph:
1. Go to Jenkins Dashboard.
2. Click on maven-job.
3. Scroll down, and you’ll see a Test Result Trend Graph.
4. The graph will show:
• Blue = Successful tests
• Red = Failed tests
• Yellow = Skipped tests

5. Key Takeaways
✅ JUnit Reports are stored in target/surefire-reports/.
✅ Jenkins can visualize test trends using XML reports.
✅ Running the job multiple times generates a meaningful graph.

9. Archiving the Last Successful Artifact in


Jenkins
Objective:
• Learn how to archive artifacts in Jenkins.
• Store the last successful JAR file for easy access.
1. What is an Artifact in DevOps?
• In DevOps, an artifact is the output of the build process.
• For a Maven project, the artifact is usually a JAR file.
• The JAR is located inside:
target/*.jar

2. Find the JAR File in Jenkins


1. Run a Build in Jenkins.
2. Go to Console Output and look for the Maven package step.
3. Run the following inside the Jenkins container to verify:
ls /var/jenkins_home/workspace/maven-job/target/*.jar

3. Configure Jenkins to Archive Artifacts


Steps to Enable Artifact Archiving:
1. Go to Jenkins Dashboard → Select maven-job.
2. Click Configure.
3. Scroll down to Post-Build Actions.
4. Click Add Post-Build Action → Select Archive the Artifacts.
5. In the "Files to archive" field, enter:
target/*.jar

6. Click Advanced and check the box:


✅ "Only archive artifacts if the build is successful"
7. Click Save.

4. Run the Jenkins Job and Verify


How to Trigger a Build?
• Click Build Now.
• Wait for the build to finish.

Where to Find the Archived Artifact?


• Go to maven-job → Scroll down.
• You will see "Last Successful Artifacts".
• Click on the JAR file to download it.

5. Key Takeaways
✅ Artifacts are build outputs like JARs.
✅ Jenkins can automatically archive successful builds.
✅ You can easily download the last successful artifact.

10. Sending Email Notifications in Jenkins for


Maven Projects
Objective:
• Configure Jenkins to send email notifications for build status.
• Get alerts when a build fails or succeeds.

1. Why Use Email Notifications?


✅ Notifies developers immediately when a build fails.
✅ Provides error details in the email.
✅ Confirms when a build is fixed (back to normal).

2. Configure Email Notifications in Jenkins


Step 1: Install Email Plugin
1. Go to Jenkins Dashboard → Click on Manage Jenkins.
2. Select Manage Plugins → Go to Available Plugins.
3. Search for Email Extension Plugin and install it.
4. Restart Jenkins.

Step 2: Configure Jenkins Email Settings


1. Go to Manage Jenkins → Click Configure System.
2. Scroll to E-mail Notification.
3. In SMTP Server, enter your email provider's SMTP details:
• Gmail: smtp.gmail.com
• Outlook: smtp.office365.com
• Yahoo: smtp.mail.yahoo.com
4. Check ✅ Use SMTP Authentication and enter your email credentials.
5. Check ✅ Use SSL (for secure connections).
6. Set SMTP Port:
• Gmail: 465 (SSL) or 587 (TLS)
• Outlook: 587
7. Click Apply & Save.

Step 3: Add Email Notification to Your Job


1. Go to Jenkins Dashboard → Select your Maven project.
2. Click Configure.
3. Scroll to Post-Build Actions → Click Add Post-Build Action.
4. Select E-mail Notification.
5. Enter your email (or multiple emails separated by commas).
6. Check ✅ Send e-mail for every unstable build.
7. Click Save.

3. Test Email Notifications


Scenario 1: Trigger a Failed Build
• Modify a Maven command to introduce an error (e.g., use an invalid flag).
• Example: Add this incorrect command in your build step:
mvn clean package -invalidFlag

• Click Build Now.


• The build will fail, and an email notification will be sent.
• Check your inbox for an email with the error details.

Scenario 2: Fix the Build & Get a Success Email


• Remove the incorrect flag and trigger a new build.
• If successful, you will receive an email stating:
"Your build is back to normal." 🎉

4. Key Takeaways
✅ Jenkins can send automatic email alerts for builds.
✅ Failure notifications help developers fix issues faster.
✅ Success notifications confirm when a build is back to normal.

You might also like