0% found this document useful (0 votes)
5 views

Unit 3 - DO

The document provides an overview of Jenkins, an open-source automation tool for continuous integration (CI) that simplifies the software development process. It details Jenkins' features, advantages, and disadvantages, as well as installation steps, configuration, job creation, and the use of plugins to enhance functionality. Additionally, it explains the architecture of Jenkins, including its master-slave setup, and outlines various job types and build triggers available within the platform.

Uploaded by

gowthamj22it
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)
5 views

Unit 3 - DO

The document provides an overview of Jenkins, an open-source automation tool for continuous integration (CI) that simplifies the software development process. It details Jenkins' features, advantages, and disadvantages, as well as installation steps, configuration, job creation, and the use of plugins to enhance functionality. Additionally, it explains the architecture of Jenkins, including its master-slave setup, and outlines various job types and build triggers available within the platform.

Uploaded by

gowthamj22it
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/ 55

PSNA COLLEGE OF ENGINEERING AND TECHNOLOGY, DINDIGUL – 624622.

(An Autonomous Institution Affiliated to Anna University, Chennai)


UNIT 3 – CONTINUOUS INTEGRATION USING JENKINS
INTRODUCTION TO JENKINS:
 Jenkins is a open source automation tool which allows contiguous integration (CI).
It is written in Java.
 Jenkins build and test our software projects continuously which becomes easy for
developers to integrate the changes in the project.
 Jenkins can integrate all types of development lifecycle processes including build,
document, test, package, phase, deploy and so on.
 Jenkins is a popular tool in DevOps community because it allows to automate the
software development process, thereby reducing the cost of manual testing and
increasing quality.
 Jenkins supports large number of plugins which makes it easy to configure and
customize any project.
Features of Jenkins:
Following are the features of Jenkins
1. Easy Installation: Jenkins has executable packages that are quick to install on
Windows, Linux and mac OS. It is just self-contained Java program that can be set
up easily.
2. Easy Configuration: Jenkins can be easily configured with the help of web
interface including error checks arid a built-in help feature.
3. Free Open Source: Jenkins is an open source project which is entirely free to use.
It has supporting developer community.
4. Available Plugin: In Jenkins thousands of plugins are available for large degree of
customizability. The developers can integrate these plugins with development and
testing tools.
5. Easy Distribution: Jenkins can easily distribute work across multiple machines for
faster builds, tests and deployments across multiple platforms.
Advantages and Disadvantages:
Advantages:
1. Free to use: Jenkins is an open source tool. We do not have to pay anything to use
Jenkins.
2. Build automation: Jenkins is a automation tool used to trigger automatic builds.
This feature allows continuous integration and continuous development.
3. Rich plugin ecosystem: Jenkins has large number of plugins that makes building,
deploying, automating across various platforms.
4. Platform independence: Jenkins can be easily used on several platforms and
operating systems such as Windows, Linux, Mac. Hence it is adaptable to different
project environment.
5. User friendly and easy to install: The installation process of Jenkins is very
simple. The user interface of Jenkins is intuitive and simple.
Disadvantages:
1. Developer centric: Jenkins is developer centric and the person using Jenkins
must have developer experience to use Jenkins.
2. Maintenance overhead: Running and maintaining Jenkins server requires effort,
including updates, plugin managements and server maintenance.
3. Changes in the settings creates problem: The continuous integration breaks
whenever changes occur in the settings.
INSTALL AND CONFIGURE JENKINS:
 Since Jenkins run on Java, the latest version of Java Development Kit (JDK) or
Java Runtime Environment (JRE) must be present on your system before starting
Jenkins.
 Following are the steps to be followed for installation of Jenkins
Step 1: Go to the web site https://www.ienkins.io/download/ and select the platform
on which the Jenkins is to be installed. I have installed Jenkins on Windows platform.
Step 2: Once the download is complete, run the jenkins.msi installation file.
Step 3: The setup wizard starts as follows. Click Next button to proceed.

Step 4: Now, Select the destination folder for installation and click Next button.

Step 5: On next screen select “RunService as LocalSystem”. This option doesn’t


require you to enter user login data. Instead, it grants Jenkins full access to your system
and services.
Click Next button. Select the default JDK folder by clicking on Next button. Finally click
on Install to start installation.
Step 6: Once the installation is complete, Click Finish to exit the installation wizard.

After completing the installation process, we need to unlock Jenkins.


Step 1: Open some suitable web browser, navigate to the port number you selected
during the installation. By default the port number is 8080. I haven't changed the
default port number, so I will use the URL as http:localhost:8080/
Step 2: Navigate to the location on your system specified by the Unblock Jenkins page.
The location is
C:\ProgramData\Jenkins\.jenkins\seccrets\initialAdminPassword
Open the initialAdminPassword file using a text editor such as Notepad. Copy the
password from the initialAdminPassword file.

Paste the password in the Administrator password field on the Unblock Jenkins page
and click Continue to proceed.
Step 3: Now, enter the required information on the Create First Admin User page. Click
Save and Continue to proceed.

Step 4: On the Instance Configuration page, confirm the port number you want
Jenkins to use and click Save and Finish to finish the initial customization.

That’s it. The Jenkins Configuration is done.


The Jenkins dashboard appears as follows -

Concept of Continuous Integration:


 The continuous integration is a development practice in which developers commit
the changes to the source code in shared repository quiet often. Every commit
(some changes in the source code) made in the repository is then built. This allows
development team to detect any problem efficiently.
 In continuous integration whenever the code commit occurs a build must be
tiggered. The job of tiggering the build for every commit can be automated by
Jenkins. Hence Jenkins is known as most mature continuous integration tool.
JENKINS ARCHITECTURE OVERVIEW:
Jenkins Workflow:
 The workflow is represented by the following figure.

Fig: Jenkins workflow


 The developers commit the code to source code repository. The typical source code
repository commonly used now a days is GitHub. Jenkins checks the repository at
regular intervals for noticing the changes committed in the repository.
 When Jenkins server finds that the changes are committed in the repository, then it
starts preparing a new build.
 If the build fails, then developers are notified about it.
 If the build is successful, then Jenkins server deploys the build on test server.
 The test server tests the build and generates the feedback. The Jenkins server gets
this feedback and notifies about build and test results to developers.
 If everything is perfect, then build is deployed on production server.
 In all the above activities, Jenkins server continuously verifies the code repository
for changes made in the source code. The above activities are repeated
continuously.
Jenkins Architecture:
 Jenkins architecture is a distributed architecture. It manages the distributed
builds using Master-slave architecture.
 The TCP/IP protocol is used to communicate between Master and Slave.
 The Jenkins architecture comprises of two components -
i) Jenkins Master/Server
ii) Jenkins Node/Slave/Build Server
i) Jenkins Master:
 The Master is responsible for -
a. scheduling the jobs
b. assigning them to slaves
c. sending builds to slaves for execution
d. to monitor the status of every slave
e. retrieve the build results from slaves
f. display the results obtained from slaves on console
ii) Jenkins slave:
 Jenkins slave run on remote server. The building jobs dispatched by the
master are executed by slaves. The Jenkins slaves are compatible with all the
operating systems. The Jenkins slave can be configured on any server
including Windows, Linux and Mac.

Fig: Jenkins architecture


Creating and Configuring a Jenkins Job:
 Jenkins is one of DevOps’s most widely adopted Continuous Integration (CI)
solutions.
 Jenkins CI allows developers to automate building, testing and deploying code
effortlessly.
 Jenkins jobs focuses on building and testing code continuously so that any changes
made in the source code are easily integrated into the build.
 Jenkins job is nothing but a specific task or set of tasks that are automated and
managed by Jenkins automation server. These jobs are a significant part of
Jenkins's build process.
 Jenkins job is created by using following steps
1. Go to the Jenkins dashboard and click on New Item.
2. In the Enter an item name field, enter a name for the job.
3. Select the type of job you want to create. For example, you can create a
freestyle project, a pipeline, or a multibranch pipeline.
4. Give the description of your job in the Description box.
5. In the Source Code Management section, specify the location of your source
code. If it is on the GitHub repository then specify the URL of your repository.
6. In the Build section, specify the steps that you want Jenkins to perform when
the job is run.
7. In the Post-build actions section, specify the actions that you want Jenkins to
perform after the job is run. For instance - deploying the war file in Tomcat
server.
8. Click on Apply and Save.
9. Finally the job can be run by clicking the Build Now button. The output can
be viewed on Console Output.
 Jenkins allows users to create and configure jobs using its graphical interface.
Following steps are described in detail along with necessary screenshots.
Step 1: Enter user name and password which you have set up during installation. I have
set it as username: admin and password: admin.
Step 2: Next screen will be a Welcome screen. Click on Create a job option.

Step 3: Enter the item name on the next screen, I have given the name as welcome.
Then clicked on Freestyle project and then clicked the ok button.

Thus the job gets crated in Jenkins.


Step 4: On the next screen, we have to configure the job. Enter some description about
the job.
Now click on Build periodically. Enter five stars with space in each star. This means
that after every minute build the application periodically.

Then on Build Steps, select Execute Windows batch command.

Enter the command -


javac welcome.java
java welcome
Then Click Apply and then click on Save.
Step 5: Open the folder C:\ProgramData\Jenkins\.jenkins'\workspace\welcome and
save the following java file as follows -
welcome.java
public class welcome
{
public static void main (String args [])
{
System.out.println (“Welcome to first Job of Jenkins”);
}
}
Step 6: On the Jenkins page in the Build History can be checked. We get the build
periodically. That means after each minute the job is executed. Click on the build
number with #.

Then click on Console Output. The output will be displayed.

Congratulations!!! we have executed our first Jenkins Job in Java using Jenkins.
Types of Jobs:
 There are different types of jobs available which are intended for different purposes.
1. Freestyle Project: Jenkins freestyle projects allow users to automate simple
jobs, such as running tests, creating and packaging applications, producing
reports, or executing commands. Freestyle projects are repeatable and contain
both build steps and post-build actions.
2. Maven Project: For managing and building the Maven projects using Jenkins,
this type of Job is used.
3. Pipeline: The pipeline job is used when working on long running activities.
4. Multi-Configuration Project: For the projects that require multiple
configurations, this option is selected for creating the Jenkins job.
5. Github Organization: If your project is hosted on GitHub, this job type allows
Jenkins to automatically scan and build repositories within a GitHub
organization.
Build Triggers:
 The Build trigger option can be seen in Jenkins Configuration settings.
 These are the most common Jenkins build triggers:
 Trigger builds remotely: If we want to trigger our project built from anywhere
anytime then we should select Trigger builds remotely option. When we
select the option “Trigger builds remotely” then we need to provide an
authorization token.
 Build after other projects are built: If your project depends on another
project build then you should select Build after other projects are built option
from the build triggers. In this option, we must specify the project name in
projects to watch field section.
 Build periodically: If you want to schedule your project build periodically then
you should select the Build periodically option from the build triggers. You
have to enter the schedule for periodic building using cron expression. Each
line consists of 5 fields separated by TAB or whitespace. Cron is a command-
line utility that allows the developers and system administrators to schedule
the tasks that nm in the background at regular intervals. The different fields of
cron expression are as follows -
 MINUTES - Minutes in one hour (0 - 59)
 HOURS - Hours in one day (0-23)
 DAYMONTH- Day in a month (1-31)
 MONTH - Month in a year (-12)
 DAYWEEK - Day of the week (0 -7) where 0 and 7 are Sunday
 The *specifies all the valid values.
 M-N defines a range of values.
 M-NIX or */X -defines the steps by intervals of x through the specified
range.
 A,B, ... Z- enumerates multiple values.
 An empty line that starts with a # symbol is treated as a comment and will
be ignored.
For example-
# every single minute
*****
# every fifteen minutes (perhaps at :07, :22, ·37,:52)
H/15 * * * *
# every ten minutes in the first half of every hour (three times, perhaps at
:04, :14, :24)
H(0-29)/10
# once every two hours at 45 minutes past the hour starting at 9:45 AM
and finishing at 3 :45 PM every weekday.
45-16/2 * * 1-5
 GitHub hook trigger for GITScm polling: A webhook is an HTTP callback, an
HTTP POST that occurs when something happens through a simple event-
notification via HTTP POST. GitHub webhooks in Jenkins are used to trigger
the build whenever a developer commits something to the branch, on GitHub.
 Poll SCM :Poll SCM periodically polls the SCM to check whether changes were
made(i.e. new commits in GitHub repository) and builds the project if new
commits were pushed since the last build. We must schedule the polling
duration in the scheduler field. Using the cron expressions we can specify the
schedule.
INTRODUCTION TO PLUGINS:
 For enhancing the functionality of Jenkins, we use plugins.
 There are thousands of different plugins which can be installed on Jenkins
controller or can be integrated with some build tools, cloud providers and so on.
 A plugin is written in Java.
 Plugins use their own set of Java Annotations and design patterns that define how
the plugin is instantiated, extension points, the function of the plugin and the UI
representation in the Jenkins Web UI.
Benefits of using Plugins:
Following are some benefits that are observed when the Jenkins plugins are used
1. Extended Functionality: Plugins can be used to add new features to Jenkins. Many
plugins are open-source and maintained by the Jenkins community. This means you
can benefit from the contributions and improvements made by a large user base.
2. Task Automation: Plugins can be used to automate various tasks related-to
software development such as building, testing, deployment of library files to
executable environment.
3. Scalability: We can add or remove the plugins as per the requirements of our project
and thereby Jenkins meets the requirements of organization.
4. Security: Jenkins plugins are useful to make the job secure by integrating with
security tools, vulnerability scanners.
5. Continuous Improvement: Jenkins is an automated tool. Developers continuously
create new plugins or improve the existing ones. Thus continuous improvement is
made with latest technologies.
6. Increased Flexibility: Plugins can be used to increase. the flexibility of Jenkins. For
example, Amazon EC2 plugin allows to deploy the application from cloud platform or
Gitplugin allows you to deploy the application from GitHub repository. There are
various ways by which the desired activity can be carried out in Jenkins.
Adding Plugins to Jenkins:
 The simplest and most common way of installing plugins is through the Manage
Jenkins > Plugins view, available to administrators of a Jenkins environment.
 Locate the desired plugin from the list or else, you can search for the plugin by
typing plugin’s names. Suppose we wish to install HTML Publisher plugin then we
can either locate it in the list or we can simply type the name of that plugin in the
search window.
Then click Install button which is present at the top right corner. The plugin gets
installed.

COMMONLY USED PLUGINS:


Following is a list of some popularly used plugins are -
1. Git Plugin: The git plugin provides fundamental git operations for Jenkins projects.
It can poll, fetch, checkout, branch, list, merge, tag and push repositories.
2. Docker Plugin: The Jenkins cloud plugin for Docker is the most effective solution for
DevOps engineers to integrate Jenkins with Docker.
3. Amazon EC2 Plugin: Amazon EC2 plugin lets Jenkins start up new EC2 or
Eucalyptus agents on demand and shut them down when they are no longer needed.
4. SonarQube Plugin: SonarQube is an open-source tool used for continuous code
quality inspection. The Jenkins monitoring plugin allows you to integrate SonarQube
into Jenkins so that you can easily analyze a code while running a Jenkins job that
comes with SonarQube execution.
5. Jira Plugin: Jira plugin is one of the most popular plugin. It is an open-source
plugin that integrates Jenkins with the Atlassian Jira Software (both Cloud and
Server versions), enabling the DevOps teams more visibility into the development
pipeline.
Git Plugin:
 The Git plugin is used to perform fundamental git operations for Jenkins project.
When the Git plugin is installed in Jenkins then we can perform pull, fetch, branch,
list, merge or push operations.
How to install Git Plugin?
 For installing the Git plugin just login to the Jenkins and click the Manage Jenkins.
Open the plugins section and install the GitHub plugin.

 Once the Jenkins Git Plugin is installed and configured, our Jenkins build jobs can
poll any local or remote repositories for new commits. The cron expression is used
for job scheduling periodically.
Example Demo:
Step 1: Create a simple Java program. I have created a folder named MyJavaPrograms
and inside it created a simple Java program as follows
test.java
public class test
{
public static void main(String args [])
{
for (int i=1; i<=5; i++)
System.out.println (“Welcome Anuradha”);
}
}
Step 2: Open the command prompt, switch to that folder and execute the above Java
program. It is illustrated by following screenshot.
Step 3: Now we will create a Git repository and push this repository on GitHub.
First of all we will initialize the Git repository my using git init command.

then add the java and class files to git repository -

Now we will create a repository on GitHub and then push the above committed Git
repository on the GitHub.
Open a web browser, and login to www.GitHub.com. Create a repository by the name
MyJavaPrograms.
then copy the URL of this repository.
HTTPS SSH https://github.com/AnurdhaP/yJavaPrograms.git
Now open the command prompt window and go to the MyJavaPrograms directory and
issue the following command.
git remote add origin https://github.com/AnurdhaP/MyJavaPrograms.git
then push the Git to GitHub repository using the command
push -u origin master
It is illustrated as follows

Now it we refresh the repository on GitHub then we can see our test.java and test.class
programs are present in that repository.

Step 4: Now create a job in Jenkins that makes use of GitHub plugin in order to access
the GitHub repository.
And configure the Jenkins job as follows -
Save this configuration.
Step 5: Now if we build this job the output that we see is as follows on Console Output.
Step 6: Now go to GitHub repository and make some changes to your test.java file and
commit these changes.

Step7: Now, if you check on the Jenkins page, it automatically executes the above
updated test.java file and creates a build. It is as follows.-

Note that Jenkins builds the job automatically on every GitHub repository changes
we need not have to build it explicitly.

Parameter Plugin:
We can configure our job by adding parameters. The Jenkins can then be build with
parameters. We can add parameters to either existing job or we can create a new job
with parameters.
Example Demo:
Step 1: Click on New item and create a job. I have created a job by the name Welcome.
Step 2: Click on the existing job and configure it with parameters.
Step 3: Check the option “This project is parameterized”. Select the String
Parameter. Create some string parameter. I have created a parameter named Username
and default value to it.

Step 4: Under the Build Steps section, using echo command I tried to display the
parameter value.
Step 5: Click on Apply and then Save.
Step 6: Select Build with parameters option.

We get the default value displayed on the screen.


We can change the username as well. Suppose I changed the Username as Anand then
click the Build, we get the console output as follows -

Thus we set variety of parameters to the Jenkins job. We can set the Boolean parameter,
choice parameter, credentials, file parameter, password parameter and so on.

HTML Publisher Report Plugin:


 This plugin is used to generate and publish the HTML-based reports as a part of
build and deployment stage. While using this plugin mainly following configurations
are required in Jenkins.
 Report Directory: Specify the directory where our HTML reports are generated
during the build or test execution. (Note that: in the following Example Demo we
have given the path of test-output directory of the Selenium test application
project which we have created with the help of Maven).
 Index Page: Specify the main HTML file (often named “index.html”) that serves
as the entry point to the HTML report.
 Report Title: We normally have to set a custom title for our report.
Advantages:
• The Jenkins HTML Publish Report is useful plugin for generating the test reports, code
quality reports, or documentation. These reports are then automatically made available
to all the members of the development team. This make the developers aware about the
number of test cases getting executed, the number of test cases that are passed or failed
and status of each test case.
How to install HTML Publisher Plugin?
Step 1: Go to Jenkins Dashboard.
Step 2: Click on the link Manage Plugin.
Step 3: Open the plugins section and install the HTML Publisher plugin.
Example Demo:
 In this demo we will work in two stages
1. During the first stage we will create a Maven project with the help of Selenium
and TestNG and write a simple test case. Selenium is a free (open-source)
automated testing framework used to automate the web browser. It allows users
to test their websites functionally on different browsers. The TestNG is an
automation testing framework in which NG stands for “Next Generation”. It
produces the HTML reports for implementation. Using this report we can easily
come to know how many test cases are passed, failed, and skipped. Build this
test case using Maven and execute it using testNG. This produces the HTML
report in “test-output” directory.
2. In the second stage, we will start the Jenkins, we will configure the path of above
Maven project and publish the HTML report which is produced by TestNG.
 Here is step by step demonstration of the entire application.
Step 1: We will create a Maven project using Selenium and TestNG framework. Open
Eclipse IDE and Create a Maven Project. Select the Create Simple Project (Skip
archetype selection) and enter the Group Id and Artifact Id as per your choice. My
project name is SeleniumDemo.
Step 2: Add the Selenium dependency in your pom.xml file as follows
<dependency>
<groupId> org.seleniumhq.selenium </groupld>
<artifactld> selenium -java </artifactld>
<version> 3.141.59 </version>
</dependency>
Save the pom.xml file.
Step 3: Now install testNG plugin. For that, from Menu select Help-> Eclipse
Marketplace.
Type TestNG in the search window. The testNG installation option will be available.
Click Install.

Then confirm the selected features by clicking on Confirm button.


In the next popup window select I Accept terms... and click on Finish button. Then it
will ask to install or not, click on install Anyway option and then restart Eclipse,
Step 4: Now we will be Installing ChromeDriver. Open the Google.com, locate the
Chrome driver and get it downloaded on your local machine.
Right click on your maven project and create a folder named drivers. Save this
downloaded chromedriver.exe file in this folder.

Step 5: Now, open the pom.xml file and add the dependencies such as testing and
junit. Also add the Maven-surefire plugin and maven-compiler plugin.
Step 6: Now, open the Maven project’s src folder, inside the test folder create some
package and create a Java class file. In my case I have created a package named
myPackage and under this package I have created a java file named myTestPage.java.

myTestPage.java
package myPackage;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class
myTestPage
{
@Test
public void myFun ()
{
System.setProperty (“webdriver.chrome.driver,”./drivers/chromedniver.exe”);
WebDriver driver = new ChromeDriver ();
driver.get (“https://google.com”);
String title = driver.g etTitle ();
System out.println (“Hey Anuradha, the tile of this page is: ”+title);
driver.quit ();
}
}
Program Explanation: In above program, we have written one test case by the function
myFun. In this function, using the Chromedriver which we have installed, we open the
web page google.com Then we try to get the tile of this page and display it on the console
using System.out statement. Finally, we quit the driver.
Step 7: Right click on the Project name in Project Explorer window, Run As-> Maven
Test.
Step 8: Now, locate the Java file myTestPage.java and right click Run As->TestNG
Test. It is as follows -
Step 9: We will get the output as follows -.

Step 10: Now, we will open the Jenkin’s page and create the HTML Publisher report for
the above SeleniumDemo project. The prerequisite to this activity is that the
HTMLPublisher report plugin must be installed in Jenkins.
 Click on New Item, Enter the Item Name and select as Freestyle project, I have
given the name HTMLReportDemo.
 Then click on configure. Write the suitable description in General section.
 Then in Build Steps and Add Build steps as Invoke top-level Maven targets
provide the Maven version, and under goals write clean test.
 Under Post Build Actions, click on Add Post Build Action and select Publish
HTML Report. Now give the path of index.html file which is created by Selenium
testing framework in Maven. It is the path of test-output folder, Also give some
suitable HTML report title.
Step 11: Click on Apply and then Save. Now build this project.
Step 12: On successful build, it creates the HTML Report as follows

 Thus using HTML Publish Report Plugin we can successfully generate HTML report
of some testing framework application.
 Troubleshooting: Sometimes, the raw file is displayed as HTML report. To get the
HTML formatted report we must click on Manage Jenkins section, scroll down and
locate Script Console section. Click on it.

and run below given command:


System.set.Property (“hudson.model DirectoryBrowserSupport.CSP”, “”)
 Then restart the Jenkins Page and Build the project once again. The HTML report
can then be displayed as given in above step.
Copy Artifact:
 The copy artifact plugin is used to copy the artifacts from one Jenkins build job to
another project, making it easier to manage and share build artifacts between
different stages or projects in the CI/ CD (Continuous Integration/Continuous
Deployment) pipeline.
Features:
1. Copying Artifact: The main purpose of copy artifact plugin is to copy files and
directories (which are known as artifacts) from one Jenkins build job to another.
These artifacts include class files, compiled binaries, test reports or any file
generated during build process.
2. Parameterized Copy: By using the Copy artifact plugin, we can dynamically specify
which artifacts to copy based on build parameters or other conditions. This flexibility
allows to tailor the copy process.
3. Filtering Artifacts: Using the wildcards and regular expressions we can specify
which artifacts to be copied. This feature is useful when we are dealing with large
number of files and directories and want to copy only those files that are meets our
requirements.
4. Build Dependencies: The copy artifact plugin is used to build dependencies between
jobs. This ensures that the required artifacts are available for the downstream jobs.
The downstream job is the one that is triggered after the actual job is triggered.
How to install copy artifact plugin?
Step 1: Start the Jenkins tool by entering the login arid password.
Step 2: Click on Manage Jenkins. Click on Plugins.
Step 3: In the search window, type the name copy Artifact.
Step 4: The plugin name will be displayed if it is not already installed. Select it.

then click on Install. The plugin gets installed.


Example Demo:
Let us discuss how to use Copy Artifact plugin.
Step 1: Create a new Job by clicking on item New Item. Give some name to your job. I
have given the name Appl and selected the Freestyle Project.
Step 2: Give suitable description in the description box.
Step 3: Under the source code management, click on Git option and specify the
repository URL of GitHub.
Step 4: Under the Build Steps section, choose the Execute Windows batch command
option. And type the javac and java commands.

Step 5: Click in Apply and Save.


Step 6: Select the Build Now option. On successful built, the test.class file gets
generated in the Jenkins workspace of the Appl job.

Step 7: Now we have to copy test.class file from the workspace of Appl to another job.
For that purpose we will create another Job named App2 by clicking New Item. Select
the Freestyle Project.
Step 8: Then configure the Build Steps by selecting the option Copy artifacts from
another project as follows -
 First of all give the name of the project from which you want to copy the files. In
mycase it is Appl.
 Then select the option “copy from WORKSPACE of latest completed build”.
 Give the regular expression **/*.* Here’s a breakdown of what **/*.* means:
 **: The double asterisk (**) is a wildcard that matches zero or more directories
and subdirectories. It's often used to recursively search through all directories
and subdirectories.
 /: The forward slash (/) is used as a directory separator, typically on Unix-like
systems.
 *.*: This part of the regular expression is used to match files with an extension.
In regular expressions, the symbol represents “zero or more” of the preceding
character or pattern, and the . character is used to match any character. So, *.*
essentially matches any file with any extension.
So, when you use the regular expression **/*.* in a Jenkins build configuration,
you are instructing Jenkins to include all files with any extension (*.*) located in
any directory and subdirectory (**) within the workspace or specified location.

Add one more Build Step and select Execute Windows batch Command. Give the
command dir so that the name of files and directories that are copied from App1 to
App2 will be displayed on the Console.
Click Apply and Save.
Step 9: Now Build this project (App2). The output will be as follows

Note that the git repository and the files from that repository are copied from the
workspace of App1 to App2. Also note that test.class and test.java files are copied to
the workspace of App2.
Extended Choice Parameters:
 The extended choice parameters allows you to create more advanced and dynamic
choice parameters in your Jenkins build jobs.
Features:
 Parameter types: The extended choice parameter plugin extends the basic
parameter types in Jenkins by offering various advanced parameter types. These
include:
1. Single Select: Allows users to choose a single option from a list.
2. Multi-Select: Allows users to select multiple options from a list.
3. Checkboxes: Presents options as checkboxes for multiple selections.
4. Radio Buttons: Presents options as radio buttons for single selection.
5. PTT (Progressive Trace Text): Provides a text box with autocomplete
suggestions based on the user’s input.
 Dynamic generation of choices: One of the most powerful features of this plugin is
the ability to generate choices dynamically. You can define scripts using Groovy,
JavaScript, or other scripting languages to compute the list of choices based on
certain conditions, external data sources or calculations.
 Integration with other plugins: The extended choice parameter plugin can be
integrated with other Jenkins plugins, enabling more complex and customized
workflows.
How to install extended choice parameter plugin?
Start the Jenkins tool by entering login and password. Click on Manage Jenkins. Click
on Plugins. Search for extended choice. The plugin name will be displayed.
Click install, Once it gets installed the Success message will be shown.

Example Demo:
Step 1: Create a new Job or select the existing Jenkins Job.
Step 2: Select the option This project is parameterized and select the option Extended
Choice Parameter.
Step 3: Click Apply and Save.
Step 4: Click Build with Parameters, and you will get

Click on In-process Script Approval to approve the Groovy script.

Click on Approve button.


Step 5: Now again click on Build with Parameters and the list of browsers which we
have mentioned in above Groovy script will be displayed.

CONFIGURING JENKINS TO WORK WITH JAVA, GIT AND MAVEN:


 In this section, we will create an application using Maven, Git and Jenkins. This
application will be created in three stages -
 In stage 1 we will create a Maven Web application.
 In the stage 2, we will push this Maven Web application on GitHub by creating
a repository for it.
 In the stage 3, we will configure the above created GitHub repository and
Build the job using Maven Goals. We will periodically (after every minute)
create the Build, using Jenkins automation feature. Even if any· changes are
committed in the GitHub’s repository then those changes can be reflected in
the latest Build. Thus continuous integration (CI) is encorporated.
Stage 1: Create a Maven Web Application Project
 Using an IDE like Eclipse we can create a simple Web Application in Maven.
Following are the steps to be followed for building this simple web application.
Step 1: Click on File->New->Maven Project. Following pop-up window will appear -

Just click Next button without selecting any archetype over here. Another window will
appear as given below - Select the maven-archetype-webapp.
Then click the Next button. Provide the Group Id and Artifact Id as per your choice.

Click the Finish Button.


Step 2: In the Project Explorer window, right-click on the project select properties->
Java Build Path.

Click on libraries path and click on JRE System Libraries and Edit it by giving the path
of JDK. (Note that Java must be installed prior to this Maven web application building)

Click On Finish button. Then click on Apply and close.


Step 3: The project structure of your Maven Web Application project is as follows-

Just open the index.jsp file and edit it. I have edited it as follows -
index.jsp
<IDOCTYPE html>
<html>
<body>
<h2> Welcome Anuradhal! </h2>
</body>
</html>
Step 4: Now edit pom.xml by adding some dependencies.
Add Jakarta Servlet dependency in pom.xml file. The dependency code can be
obtained from mvrepository.com. The code for the dependency is as follows -
<!-- https://mvrepository .com/artifact/jakarta.servlet/jakarta.serv let-api -->
<dependency>
<groupld> jakarta .servlet </groupld>
<artifactld> jakarta.serv let-api </artifactld>
<version> 6.0.0 </version>
<scope> provided </scope>
</dependency>
Step 5: Now right click on Project name in the project explorer and click Run As
Select Maven install. This will build your web application.
The Build Success message will be displayed on the Console window.
Step 6: Right click on project name and select Run As-> Run on Server. This will lead
to configuration of Tomcat folder which is installed on your local machine.

Once the Tomcat server gets started, following output can be viewed in the web browser.
Stage 2: Pushing the Maven Web Application on Git
 The prerequisite here is to have a account on Github.
 Now we will use following steps to push the above Maven Web app on GitHub. This
is how we try to link our web application to Github.
Step 1: Sign in the Github.com by entering your username and password.
Give the repository name. Note that this name must be the same name as of your Maven
project (we have created in Stage1).
Click on-New and then type the name of the Repository

Step 2: Now click on Settings ->Developer Settings, click on Personal access tokens.
Click on Generate New Token in order to create a token. This token is generated so that
any third party application can access to this repository without re-entering the login
name and password.

I have given the token name as mytoken and no-expiration to this token. Selected the
repo checkbox.
Then click on Generate Token button. A token will get generated.
Step 3: Now in the Eclipse IDE, from the menu bar, click on Window->Show view-
>other. Select the Git Repositories.

Step 4: On the GitHub.com, just copy the URL link of your repository.
Step 5: Now, inside the Eclipse, click on Clone a Git repository.

Immediately a pop up window will appear as follows -

Click Next button.


Click the Finish button.
Right click on the project click Team-> Share Project.

Click on Finish button. Now from menu bar of Eclipse, select Window->show
view->other. Select the Git Staging. Now drag the index.jsp and pom.xml file from
Unstaged Changes area to Staged Changes.
Now type some commit message and click on Commit and Push.

Then a pop up window will appear on which as a user-name we have to enter the
Github’s user email id. And as a password it has to copy the Personal access token
from Github.

Thus the copied token is pasted as a password in Eclipse. Check the checkbox Store in
Secure Store. Then click Log in button.
Then Push the app.

Step 6: Now, in the Web browser just refresh the GitHub.com. We can now see our Web
Application on Git Hub.

That’s it, we have Pushed our application on GitHub.


Stage 3: Performing Cl-CD using Jenkins
 Open the Jenkins page using Web browser. Enter the user name and password.
Step 1: First of click on Manage Jenkins. Select the plugins option and install the
deploy to Container plugin. This plugin will allow us to deploy our Web Application to
Tomcat Server.
Step 2: Now click on New Item to create a Job. Enter the name of the Job. I prefer to
give the same name as my web application. Then click on Freestyle project option.
Then click Ok button.

Step 3: In the Description box, write the description of your project. Then select option
GitHub project and enter the URL of your repository which you have created in Stage 2.
This URL can be copied from the GitHub.com by opening your repository.

The above URL is copied and pasted in Jenkins page.


Step 4: Under Source Code Management section select the GitHub project option and
paste the URL of your repository on GitHub.

There are no credentials as your repository is public. If the repository is private then we
have to provide the credentials of user name and password of our GitHub account.
Step 5: If the branch of your GitHub repository is a master branch then keep it as it is.

Step 6: In the Build Trigger section select the option Poll SCM and give five stars with a
space in between. The meaning of this is that when ever you make changes in your
GitHub repository then the Build will be triggered in Jenkins. And after each one minute
Jenkins will make a Build. It will get your code from Git Repository, will make a War file
with the help of Maven command. The five stars indicate a one minute time frame.

Step 7: Under Build steps add two build steps


First Step: Execute Window batch command as “cd MyWebApp”. This switch to the
folder MyWebApp.
Second Step: Invoke top-level Maven target. Select the your Maven version Then
under Goals given the Maven command to clean, package or build.
If you click the Advanced tab then you can also specify the path for pom.xml file which
will be fetched from GitHub to Jenkins workspace. Note that this pom.xml will be used
by Jenkins for creating a war file of your web application project.
Note that in the following window we have mentioned the location of the pom.xml file
which Jenkins will fetch from GitHub when its build is triggered. This is a path of
Jenkins workspace directory.
Step 8: Under Post Build option we have to select Tomcat Web container for deploying
the war file which Jenkins will generate for our web application. So we must select
Deploy war/ear to container as a Post Build action.

We have to specify the path of war file.


Then select the Tomcat Container, add the credentials of your Tomcat (admin and
password of your tomcat) and tomcat URL.
The Tomcat credentials can be added by clicking the Add button. By clicking the Add
button we can create that credential. I have created a credential named
myTomcatCredential.

Then give the Tomcat URL. All the above activities are illustrated in following screenshot.
Finally Click Apply and Save.
Step 9: Start your local Tomcat server. Then on Jenkins page, click the Build Now for
building the automation.
On Successful Build we get following output on Console.

Step 10: Open the web browser arid enter the URL of your Web Application.
Step 11: If you make any changes in your repository file on GitHub then accordingly
Build will be generated by Jenkins automatically and if you refresh the Web application
URL, those changes will be reflected automatically.

The commit the changes GitHub. Now the output will be -

Thus when developers edit the code, those changes will be automatically reflected as an
output, if we use Jenkins as an automated tool. Thus it facilitates us with Continuous
Integration and Continuous Development!!!
CREATING A JENKINS BUILD AND JENKINS WORKSPACE:
 In Jenkins Build is a process of compiling the source code, running tests, creating
deployable artifact such as binary executable, a library or web application.
Following activities occur during the Jenkins Build process.
1. Source Code Retrieval: In this step the source code is retrieved by the version
control system such as Git or Subversion. Sometimes, the source code can also
be retrieved from the local storage disk.
2. Workspace Creation: Jenkins creates a working directory which is known as
workspace where it stores all the files necessary for the build process.
3. Build Environment Configuration: Jenkins allows to specify the files, libraries
and dependencies required for the build, which is called configuration process.
4. Build process: Following activities are carried out during the actual build
process -
a. Compilation: Source code is compiled into executable binaries or libraries.
b. Testing: Running test cases to check the correctness of the source code.
c. Artifact Generation: The artifacts such as jar or war files are generated.
5. Reporting: Jenkins collect and generate reports during the build process. For
instance the HTML report can be published by Jenkins.
6. Artifact Archiving: Jenkins collect the artifact that are ready for deployment.
7. Deployment: The artifacts that are deployed in the executable environment. For
example if the war file is generated during the Jenkins Build can be deployed on
the Tomcat container for execution.
8. Logging: Jenkins maintains detailed logs of each build, including console
output and build artifact.
Steps to Create Jenkins Build:
Step 1: Open the web browser and access the web interface of Jenkins by providing the
username and password.
Step 2: Click on “New Item” on the Jenkins dashboard to create a new job or select the
already created job. Once job is ready, click on Build Now.

Step 3: If there exists some errors, then Jenkins will display the errors on Console
output otherwise the actual output can be seen on the console.
The workspace for the Jenkins job gets created automatically. Sample workspace is
represented by following screenshot.

You might also like