0% found this document useful (0 votes)
1 views91 pages

Devops Report

Uploaded by

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

Devops Report

Uploaded by

Dhrithi J
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Devops

Program 1:
Introduction to Maven and Gradle: Overview of Build Automation Tools,
Key Differences Between Maven and Gradle, Installation and Setup

Overview of Build Automation Tools

Build automation tools are essential in modern software development for streamlining the
process of compiling code, running tests, packaging applications, and deploying them. These
tools help eliminate manual errors, enhance productivity, and ensure consistency across
environments. They play a critical role in Continuous Integration and Continuous
Deployment (CI/CD) pipelines.

Types of Build Automation Tools

1. Build Scripting Tools: Automate tasks using custom scripts.


Examples: Make, Ant

2. Build Management Tools: Handle dependencies, compilation, and


packaging. Examples: Maven, Gradle

3. CI/CD Tools: Integrate build, test, and deployment


workflows. Examples: Jenkins, GitLab CI/CD, GitHub
Actions

Popular Tools and Features:

Tool Supported Languages Key Features

Apache Maven Java, Scala Dependency management, standardized lifecycle

Gradle Java, Groovy, Kotlin Incremental builds, high performance

CMake C, C++ Cross-platform build configuration

Bazel Multi-language Scalable builds, used by Google

Jenkins Any Plugin-rich CI/CD automation

GitHub Actions Any CI/CD directly integrated with GitHub

Typical Build Lifecycle


1. Clean – Remove previous build outputs
2. Compile – Convert source code into binaries
3. Test – Run automated tests
4. Package – Bundle output for release
5. Deploy – Deliver application to target environment
Dept. of CSE, BIT 2024-25 1
Devops

Key Benefits
● Consistency: Ensures uniform builds across environments
● Efficiency: Saves time through automation
● Reliability: Reduces manual errors and improves reproducibility
● Productivity: Developers focus on feature development
● Integration: Seamlessly connects with other development tools

Key Differences Between Maven and Gradle


1. Build Language:
Maven uses XML for its configuration through [Link], making it more verbose
but predictable. Gradle uses a more expressive domain-specific language (DSL)
based on Groovy or Kotlin, allowing greater flexibility.
2. Performance:
Gradle is faster due to its support for incremental and parallel builds, while Maven
performs full builds each time by default.
3. Configuration Approach:
Maven follows a "convention over configuration" philosophy, making setup easier
but less flexible. Gradle allows deeper customization of the build process.
4. Dependency Management:
Both tools support strong dependency management, but Gradle offers more
flexibility and dynamic resolution.
5. Plugin System:
Gradle has a more powerful and extensible plugin system compared to Maven,
which relies on a predefined plugin structure.
6. Learning Curve:
Maven is generally easier for beginners due to its straightforward XML structure.
Gradle requires learning its scripting language, which can be more complex initially.
7. Tooling and IDE Support:
Both tools are well-supported by modern IDEs like IntelliJ IDEA and Eclipse.
8. Build Output:
Maven produces more standardized outputs, while Gradle’s outputs can vary depending on
configuration.

Dept. of CSE, BIT 2024-25 2


Devops

Installation and Setup

Java (JDK) Installation:


Step 1: Go to terminal and give the command sudo apt install openjdk-11-jdk -y
It will install the OpenJDK 17 (Java Development Kit) and accepts installation automatically.

The installation will start like this.

Step 2: Confirm the installation by running command java -version

It confirms that the JDK11 is perfectly installed.

Maven Installation:
Step 1: Go to terminal and run the command sudo apt install maven -y
It will install Apache Maven from Ubuntu's package repository.

The Installation will start like this


Step 2: To check the proper installation of Maven run the command mvn -version

It confirms that the Maven is perfectly installed.

Dept. of CSE, BIT 2024-25 3


Devops

Gradle Installation:
Step 1: Go to terminal and run the command sudo apt install gradle -y
It installs Gradle build automationtool from Ubuntu's package repository.

The Installation will start like this


Step 2: To check the proper installation of Gradle run the command gradle -version

It confirms that gradle is perfectly installed.

Dept. of CSE, BIT 2024-25 4


Devops
Program 2:
Working with Maven: Creating a Maven Project, Understanding the POM
File, Dependency Management and Plugins

Step 1: Create a Maven project by running following command into terminal:


mvn archetype:generate -DgroupId=[Link] -DartifactId=MyMavenApp
- DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

This command generates a basic Maven project structure with a sample [Link] and
[Link].

This “Build Success” will confirm that the project is created successfully
Step 2: Go to the project directory using command cd MyMavenApp
Step 3: Open and edit [Link] file using command gedit [Link]
● Go to [Link]
● Search for a dependency “junit”
● Select the latest version and copy the dependency XML snippet.
● Paste it under the <dependencies> section in [Link]
● Updated [Link]:
<project xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<modelVersion>4.0.0</modelVersion>
<groupId>[Link]</groupId>
<artifactId>MyMavenApp</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>

Dept. of CSE, BIT 2024-25 5


Devops
<name>MyMavenApp</name>
<url>[Link]
<!-- Java version configuration -->
<properties>
<[Link]>11</[Link]>
<[Link]>11</[Link]>
</properties>
<!-- Dependencies -->
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<!-- Build Plugins -->
<build>
<plugins>
<!-- Compiler Plugin -->
<plugin>
<groupId>[Link]</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
<!-- Surefire Plugin for Testing -->
<plugin>
<groupId>[Link]</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
<!-- JAR Plugin with Entry Point -->
<plugin>
<groupId>[Link]</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<archive>
<manifestEntries>
<Main-Class>[Link]</Main-Class>
</manifestEntries>

Dept. of CSE, BIT 2024-25 6


Devops
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>
Step 4: Build the project using command mvn clean install

The project building will start like this.

The “Build Success” message ensures that our Maven project is built successfully.

Step 5: Package the project using command mvn package.


Step 6: Run the test on project using command mvn test.
Step 7: To run the Maven application
● Go to target directory present in MyMavenApp using command cd target

● Execute the JAR file with the command:


java -jar [Link]
● After completing the execution, the output will look like:

This will show output as the code present in [Link] file we can edit the text to get any other
output.

Dept. of CSE, BIT 2024-25 7


Devops
Creating a Maven Project with Guava and Commons-IO
Google Guava Dependency
Guava is a set of core libraries developed by Google to fill gaps in Java's standard libraries. It
is used for:
• Collections enhancements: Multimap, BiMap, Table, ImmutableList, etc.
• Functional programming utilities: Predicates, Functions, Suppliers.
• Caching: Built-in caching mechanisms (CacheBuilder) like a mini in-memory cache.
• String utilities: Splitter, Joiner, CharMatcher.
• Concurrency: ListenableFuture, Service, and other helper classes.
• Hashing and hashing strategies: Useful for consistent hashing (e.g., Bloom
filters). Overall, Guava simplifies and improves many core Java patterns and utilities.

Apache Commons IO Dependency


Apache Commons IO is focused purely on input/output utilities, especially for file and stream
handling. It is used for:
• File operations: Easily read/write files with FileUtils.
• Stream utilities: [Link](), [Link]() — simplifies stream handling.
• Directory monitoring: FileAlterationObserver for detecting changes in a folder.
• File filtering: WildcardFileFilter, SuffixFileFilter.
Overall, Commons IO reduces boilerplate and errors when working with files or streams.

Maven Project with Guava and Commons-IO Dependencies


Create a Maven Project Using Terminal by following command:
mvn archetype: generate -DgroupId=[Link] -DartifactId=MyMavenGuavaApp -

DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Dept. of CSE, BIT 2024-25 8


Devops
Now Navigate to the Project Directory using cd MyMavenGuavaApp

Then, use tree command to check the directory structure created by our command

Edit the [Link] File to Add Dependencies using gedit [Link] and inside the
<dependencies> tag, add:
<!-- Guava Dependency -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>guava</artifactId>
<version>33.4.0-jre</version>
</dependency>
<!-- Apache Commons IO -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.18.0</version>
</dependency>
Also, under <build>, include plugins for compilation and specify the main class:
<build>
<plugins>
<plugin>
<groupId>[Link]</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source> <target>1.8</target>
</configuration>
Dept. of CSE, BIT 2024-25 9
Devops
</plugin>
<plugin>
<groupId>[Link]</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
<plugin>
<groupId>[Link]</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<archive>
<manifestEntries>
<Main-Class>[Link]</Main-Class>
</manifestEntries>
</archive>
</configuration>
</plugin>
</plugins>
</build>

Now, [Link] looks like this

Dept. of CSE, BIT 2024-25 10


Devops

Modify [Link]
Got to [Link] using cd src/main/java/com/example/ and gedit [Link] to type the file with
following code:

package [Link];
import
[Link];
import [Link];
import [Link];
import [Link];
public class App
{
public static void main( String[] args )
{
ImmutableList<String> fruits = [Link]("Apple", "Banana", "Cherry");
[Link](fruits);
File sourceFile = new
Dept. of CSE, BIT 2024-25 11
Devops
File("[Link]");

Dept. of CSE, BIT 2024-25 12


Devops
File destFile = new
File("[Link]");
try{
[Link](sourceFile, destFile);
[Link]("File copied
successfully!");
} catch (IOException e) {
[Link]("Error occurred while copying file: " + [Link]());
}
}
}

The [Link] file defines a simple Java application in the [Link] package. It uses
Guava's ImmutableList to create and print a list of fruits (Apple, Banana, Cherry). It then
defines two file objects: [Link] and [Link].

Using Apache Commons IO's [Link](), it copies the contents of the source file
to the destination file. If the copy is successful, it prints a confirmation message; otherwise,
it prints an error message.

(Updated [Link])

Dept. of CSE, BIT 2024-25 13


Devops
Build the Project using the command mvn clean install command

This compiles the project and creates a JAR in the target/ folder.
Run the Application:
If java-jar command give an error which is most probable, use the following command
mvn exec:java -[Link]=”[Link]”

This command gives error as


Error while copying file:Source ‘[Link]’ does not exist
Now, Create a Sample File to Copy using echo "My Data needs to be transferred" > [Link]

Dept. of CSE, BIT 2024-25 14


Devops
Now Run the command mvn exec:java -[Link]=”[Link]” again

The output shows file copied successfully.


We can see newly created [Link] using gedit [Link] if you are still in Project’s
directory

File content is same as the content in source file.

Dept. of CSE, BIT 2024-25 15


Devops
Program 3:
Working with Gradle: Setting Up a Gradle Project, Understanding Build Scripts
(Groovy and Kotlin DSL), Dependency Management and Task Automation

Setting Up a Gradle Project


To create a basic Gradle Project, run following commands:
mkdir my-gradle-app: to create a Gradle project directory
cd my-gradle-app: to change directory to project directory

gradle init --type java-application

Above command uses Gradle’s init method to create a basic Gradle Java application with

following directory structure:

HelloGradle/

├── [Link]

├── [Link]

├── gradle/

├── gradlew

├── [Link]

└── src/

├── main/java/[Link]

└── test/java/[Link]

Dept. of CSE, BIT 2024-25 16


Devops
tree: use tree command to check the directory structure created by our command

Files Breakdown – instead of [Link] we have four main files that have several important
information regarding the gradle application:
• [Link] – Main build script. Defines project settings, dependencies, and plugins
• [Link] – sets the project name and can include subprojects (for multi-
project builds)
• gradlew & [Link] – Gradle Wrapper scripts. Use these to run Gradle
without requiring a system install. gradlew for Unix, .bat for Windows

By default, [Link] looks like:

Dept. of CSE, BIT 2024-25 17


Devops
Go to terminal and run following commands:

gradle build: it compiles the source code and package the app

gradle run: Run the default Hello World application

We can open [Link] present inside src/main/java and observe the following contents:

Dept. of CSE, BIT 2024-25 18


Devops
Use tree command to view the updated directory structure:

Gradle lets you define and customize tasks, which are units of work like compiling code,
running tests, or packaging your app. We can use built-in tasks, or create your own.

e.g. We can add tasks like this to our [Link] file as shown below:

Here task defines a particular piece of code that is designed to do some work, ‘display’ is the
name of the task and ‘doLast’ is used append a task to queue in a way that it executes last
(alternative is ‘doFirst’ which prepend a task to queue so that it executes first)

Dept. of CSE, BIT 2024-25 19


Devops
Open [Link] using gedit and include the above task as shown below:

Run the task using following command:

gradle <task-name> (e.g. gradle display)

Dept. of CSE, BIT 2024-25 20


Devops

We can add as many tasks as we want by enclosing tasks as shown in following figure:

Run multiple tasks at once using following


command gradle task1 task2 task3 …

Understanding Build Scripts (Groovy and Kotlin DSL)

Groovy DSL (Traditional, .gradle files): Groovy DSL is the older and more widely used
syntax. e.g. [Link]
plugins
{ id
'java'
id 'application'
}
group = '[Link]'
version = '1.0.0'
repositories {
mavenCentral()
}
ependencies {
implementation '[Link]:guava:31.0.1-
jre' testImplementation 'junit:junit:4.13.2'
}
application {
mainClassName = '[Link]'
}
Dept. of CSE, BIT 2024-25 21
Devops

Kotlin DSL (Newer, .[Link] files): Kotlin DSL offers better IDE support (like auto-
completion) and type safety.
e.g. [Link]
plugins {
java
application
}
group = "[Link]"
version = "1.0.0"
repositories {
mavenCentral()
}
dependencies {
implementation("[Link]:guava:31.0.1-jre")
testImplementation("junit:junit:4.13.2")
}
application {
[Link]("[Link]")
}

Key Differences between Groovy and Kotlin DSL:

Feature Groovy DSL (.gradle) Kotlin DSL (.[Link])


Syntax Style Dynamic, flexible Statically typed, concise
IDE Support Limited auto-complete Full auto-complete in IntelliJ
Learning Curve Easier for scripting beginners Easier for Kotlin/Java devs
Type Safety No Yes
Performance Slightly slower Slightly better in large builds

Dependency Management and Task Automation

Dependency Management: Gradle manages project libraries (dependencies) by downloading


them from repositories like Maven Central or JCenter, ensuring the right versions are included
in your project.

Task Automation: Gradle automates tasks like compiling code, running tests, generating
JARs, cleaning builds, etc. You can use built-in tasks or define custom ones. There are some
Built-in Tasks in Gradle:
gradle build # Full build: compile, test, package
gradle clean # Cleans the build directory
gradle test # Runs tests
gradle run # Runs the application

Dept. of CSE, BIT 2024-25 22


Devops

Program 4:
Practical Exercise: Build and Run a Java Application with Maven, Migrate the Same
Application to Gradle

Build and Run a Java Application with Maven


To build a basic Java Application with Maven Project, run following command:
mvn archetype: generate -DgroupId=[Link] -DartifactId=maven-to-gradle \
-DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Use cd command to move to created maven-to-gradle project directory

tree: use tree command to check the directory structure created by our command

Dept. of CSE, BIT 2024-25 23


Devops

Run mvn compile to compile your project

Run mvn test to run unit tests

Run mvn package to create a JAR package

Dept. of CSE, BIT 2024-25 24


Devops

Run tree command to view directory to locate JAR file

Run following command to run JAR file


java -jar target/[Link]

Migrate the Same Application to Gradle


Inside the Maven Project directory initialize a Gradle Project using gradle init command with
type as pom, command converts [Link] structure to Gradle’s [Link].

Dept. of CSE, BIT 2024-25 25


Devops
We can view directory structure by tree command:

We can see newly created Gradle files like [Link] etc.

Run gradle build to build the application

Sometimes it runs but it can fail due to directory collision, so to prevent directory collision we can
add following piece of code to remove warnings or potential errors:

Dept. of CSE, BIT 2024-25 26


Devops

We would edit [Link] using gedit

And add the above code to it

Updated [Link] file looks like this

Dept. of CSE, BIT 2024-25 27


Devops

Run gradle build again

All the warnings and potential errors are now resolved

We can see the location of our new JAR file by tree command

Now to run migrated JAR file we can type following command java -
jar build/libs/[Link]

Dept. of CSE, BIT 2024-25 28


Devops

Program 5:
Introduction to Jenkins: What is Jenkins?, Installing Jenkins on Local or Cloud
Environment, Configuring Jenkins for First Use
What is Jenkins?

Jenkins is an open-source automation server used primarily for continuous integration (CI) and
continuous delivery (CD) in software development. Key features of Jenkins are as follows:
● Open-source and free
● Continuous Integration & Continuous Delivery (CI/CD)
● Extensible via 1,800+ plugins
● User-friendly web-based interface
● Automated testing support
● Build automation with tools like Maven, Gradle, Ant
● Supports pipeline as code (Jenkinsfile)
● Integrates with version control (Git, GitHub, Bitbucket)
● Build and package applications
● Supports distributed builds across multiple agents (master/slave architecture)
● Real-time build and test result monitoring
● Notifications via email, Slack, etc.
● Customizable build triggers (e.g., commits, schedules)
● Parallel and sequential execution of jobs
● Role-based access control and authentication

Example Use Case:


Step 1: Developer pushes code to GitHub
Step 2: Jenkins pulls the code, builds it with Maven
Step 3: Runs Junit Tests
Step 4: Deploys the WAR to Tomcat or Docker container

Dept. of CSE, BIT 2024-25 29


Devops
Installs Jenkins on Local or Cloud Environment
To install Jenkins on Local Ubuntu Linux system follow the following steps:
Run sudo apt update to update the local Ubuntu linux repository

Run sudo apt upgrade to install available upgrades for your installations

Check the version of installed JDK with java –version command

Dept. of CSE, BIT 2024-25 29


Devops
Open ubuntu Software and search for Jenkins

Select Jenkins option and click on installation

By default Jenkins will open on localhost:8080/


Configuring Jenkins for First Use

First, go to a Web Browser and type: localhost:8080/

First time, Jenkins would ask us to Unlock Jenkins

Dept. of CSE, BIT 2024-25 30


Devops

To get IntialAdminPassword :
Open /var/snap/jenkins/4865/secrets/initialAdminPassword and copy the initialAdminPassword

Dept. of CSE, BIT 2024-25 31


Devops
Copy the password and paste it in the textbox and click on Continue, then in next window Select
Install suggested plugins option; wait for the plugins to be downloaded then click continue

In Create First Admin User box, Provide Admin User credentials:

Dept. of CSE, BIT 2024-25 32


Devops
In the Instance Configuration provide Jenkins URL for your ID as shown below and your Jenkins is now
ready for first use, but still some configurations and plugins needs to be set and installed.

After this, on clicking Start Using Jenkins, we will get Jenkins home Dashboard as shown in following
figure.

Dept. of CSE, BIT 2024-25 33


Devops
Now open Manage Jenkins and click on Plugins

Now Go Available plugins and search for following essential Plugins:

1. Maven Integration Plugin


2. Gradle Integration Plugin (might be already installed check under installed plugins)
3. Pipeline: Stage View Plugin
4. GitHub Integration Plugin

Select install checkbox for all plugins and click install

Wait for them to be downloaded.

Dept. of CSE, BIT 2024-25 34


Devops
Now under Manage Jenkins, click on Tools, Under Tools click on Add JDK button and provide
JAVA_HOME path which you can find by going to Other Locations > Ubuntu > lib > jvm > java-
-openjdk-amd64 where ‘ ’ can be replaced by version of JDK installed in system, open directory
in terminal to verify its validity

(JDK Configuration)

(Example of JAVA_HOME directory)

(JAVA_HOME directory opened in Terminal)

Dept. of CSE, BIT 2024-25 35


Devops
Now for git configuration, first ensure that git is installed on system or install it using following
command:
sudo apt install git

Find path of Git by typing: ‘which git’ command

Provide name, path to git in textbox under Git Installation


e.g. Name – Default
Path to Git executable – /usr/bin/git

Dept. of CSE, BIT 2024-25 36


Devops
Do the same for Maven and Gradle

(Gradle installation with name ‘gradle’)

(Maven installation with name ‘maven’)

Now to setup GitHub Credentials go to Dashboard > Manage Jenkins then click on Credentials

In Credentials click on System, then in Global Credentials click on Add Credentials

(Credentials Dashboard)

Dept. of CSE, BIT 2024-25 37


Devops

(System Dashboard under Credentials)

(Global Credentials Dashboard)

Fill up the field under New Credentials and Save it

New GitHub Credentials can be under Global Credentials

Dept. of CSE, BIT 2024-25 38


Devops

Program 6:
Continuous Integration with Jenkins: Setting Up a CI Pipeline, Integrating Jenkins
with Maven/Gradle, Running Automated Builds and Tests

Setting up a CI Pipeline
Jenkins is an open-source automation server widely used for continuous integration and
continuous delivery (CI/CD). It helps automate the process of building, testing, and deploying
applications, making development faster and more reliable. Some of its features include:

● Pipeline as Code: Define CI/CD pipelines in a Jenkinsfile using Groovy DSL.

● Plugin Ecosystem: 1,800+ plugins for Git, Maven, Docker, Kubernetes, Slack, etc.

● Distributed Builds: Run jobs on multiple agents/nodes.

● SCM Integration: Connects with Git, GitHub, GitLab, Bitbucket, etc.

● Web UI & API: Monitor jobs and configure via browser or

API. Prerequisites for a CI Pipeline include:

1. Installed OpenJDK (Java 11+)

2. Installed Jenkins on Ubuntu

3. Accessible Jenkins Web UI (By default, on localhost:8080)

4. Configured Jenkins for First Use (i.e. unlocked through initial password)

5. Downloaded Suggested Plugins plus plugins like GitHub Integration, Maven


Integration, Gradle Integration and Pipeline: Stage View

6. Created Credentials for GitHub Login

7. ‘JenkinsFile’ (without any extension) at root directory of your Maven/Gradle Project

Dept. of CSE, BIT 2024-25 39


Devops
Integrating Jenkins with Maven

First create a maven java application using the below given command. This creates an application
named ‘maven-hello-world’.
mvn archetype: generate -DgroupId=[Link] -DartifactId=maven-hello-world \
-DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Compile the maven java app using mvn compile command

Dept. of CSE, BIT 2024-25 40


Devops
Test the application using the mvn test command

Package all the files in the maven project using mvn package command

Dept. of CSE, BIT 2024-25 41


Devops
Now we can run the created jar file:

java -jar target/[Link]

Now, inorder to do a Jenkins pipelining, we have to define the Jenkins automation script in
JenkinsFile in root directory of our project
pipeline
{ agent any
tools {
maven 'Maven'
jdk 'JDK'
}
stages {
stage('Checkout')
{ steps {
git branch: ‘master’, url: '[Link] /[Link]'
}
}
stage('Build')
{ steps {
sh 'mvn clean package'
}
}
stage('Test')
{ steps {
sh 'mvn test'
}
}
stage('Run Application')
{ steps {
sh 'java -jar target/[Link]'
}
}
}

Dept. of CSE, BIT 2024-25 42


Devops
post {
success {
echo 'Build and deployment successful!'
}
failure { echo 'Build failed!'
}
}
}
This file defines a pipeline which automates the following steps:
1. Checkout the source code from a Git repository.
2. Build the application using Maven.
3. Test, Execute the JAR file
4. Provide Basic Success/Failure handling post
actions Explanation of Code components:
1. Pipeline Block
pipeline
{ agent
any
The pipeline block is the entry point for the Jenkins pipeline.
agent any: This specifies that the pipeline can run on any available Jenkins agent (master or
slave node). In a more advanced setup, you might specify a particular agent or a Docker
container here.
2. Tools Block
tools {
maven
'Maven' jdk
'JDK'
}
The tools block allows you to specify which tools are needed to run the pipeline:
maven 'Maven': This tells Jenkins to use the Maven tool installed on the system, where
'Maven' is the name of the Maven installation as configured in Jenkins under Manage Jenkins
→ Global Tool Configuration.
jdk 'JDK': Similarly, this defines which JDK to use for the build, where 'JDK' is the name of
the JDK installation.
If you have configured Maven and JDK versions in Jenkins, this block ensures the correct

Dept. of CSE, BIT 2024-25 43


Devops
versions are used.

Dept. of CSE, BIT 2024-25 44


Devops
3. Stages Block
The stages block contains multiple stages, each representing a specific part of the build and
deployment process.
stages {
Inside the stages block, each stage corresponds to a distinct step in the CI/CD pipeline.
4. Checkout Stage
stage('Checkout') {
steps {
git branch: ‘master’, url: '[Link]
}
}
This stage is responsible for checking out (cloning) the source code from a Git repository
(master branch). The git command is used to clone the repository from GitHub:
[Link] This ensures that Jenkins always works
with the latest code from the repository.
5. Build Stage
stage('Build')
{ steps {
sh 'mvn clean package'
}
}
This stage compiles the project and creates a .jar (Java Application Archive) file using Maven.
Here, sh 'mvn clean package' command executes the mvn clean package command in the
shell. This command first using clean deletes any previously compiled artifacts then uses
package to build the project and packages it into a .jar file, ready for deployment.
6. Test Stage
stage('Test’)
{ steps {
sh ‘mvn test'
}
}
This stage executes the unit tests using Maven’s test phase
7. Run Application Stage
stage('Run Application')
{ steps {

Dept. of CSE, BIT 2024-25 45


Devops
sh 'java -jar target/[Link]'
}
}
This stage runs the packaged Java app. This will block the pipeline until the app is stopped.
For long-running apps, it's better to run in the background or manage via a service.
8. Post Actions
post {
success {
echo 'Build and deployment successful!'
}
failure {
echo 'Build failed!'
}
}
Post block defines actions to run after the pipeline, if successful log success else log failure.
9. End of Pipeline
}
}
The closing curly braces (}) mark the end of the stages block and the pipeline block.
Now we need to create a empty repository in GitHub with following credentials:

Dept. of CSE, BIT 2024-25 46


Devops
Initialize git in the maven-hello-world directory using the git init command, which initializes a
local git repository

Add the github remote repo to the local repo using the command,

git remote add origin [Link]

Add all the files and folders in the local directory to stagged stage,
git add .

Commit the added files, ones in the stagged state, using following command:
git commit -m “Initial commit”
where, -m denotes the commit message option, here with ‘Initial commit’
then to push all files to the remote github repository use following command:
git push -u origin master

Dept. of CSE, BIT 2024-25 47


Devops

(git commit)

(git push)

(Files uploaded to GitHub Repo)

Dept. of CSE, BIT 2024-25 48


Devops

Now login to Jenkins using your credentials ([Link] There click on New Item
to create a pipeline which opens a window as shown below. Enter the item name as ‘Maven-
hello-world’ and select ‘pipeline’ and then, click on ‘OK’.

Here, select the pipeline from SCM and the source to be ‘Git’ as we uploaded the Jenkins script
file onto it. Paste the GitHub Repo URL and select the Git credentials created during Jenkins
configuration. Check for the Jenkins script file name ‘JenkinsFile’, Then click on Save which
creates a pipeline configuration.

Dept. of CSE, BIT 2024-25 49


Devops

Click on ‘Build now’ to build the pipeline configurated.

Integrating Jenkins with Maven/Gradle

Create a directory named ‘GradleApp’ and navigate to it. Now, create a simple Gradle Java
Application using gradle init –type java-application

Build the gradle application using gradle build

Dept. of CSE, BIT 2024-25 50


Devops

Run the gradle application just built to see the output using gradle run

We can even add additional tasks and verify the output of the application.
Now create a Jenkins script to perform Jenkins pipelining.
pipeline {
agent any // Use any available
agent tools {
gradle 'Gradle' // Ensure this matches the name configured in Jenkins jdk 'JDK'
}
stages {
stage('Checkout')
{ steps {
git branch: 'master', url: '[Link]
}
}
stage('Build')
{ steps {
sh 'gradle build'
}
}
stage('Test')
{ steps {
sh 'gradle test'
}
}
stage('Run Application')
{ steps {
sh 'gradle run'
Dept. of CSE, BIT 2024-25 51
Devops

}
}
}
post {
success {
echo 'Build and deployment successful!'
}
failure {
echo 'Build failed!'
}
}
}
Here, JenkinsFile is similar to one we created for Maven, it only differs in the shell commands
since we need to create a Gradle Pipeline.

Create a GitHub repository named ‘GradleApp’ with public access.

Dept. of CSE, BIT 2024-25 52


Devops

Now the gradle application consists of all the requirements being required for Jenkins pipelining.
Thus initialize a local git repo, git init

Then, add the remote repo to the local repo using the following command,

git remote add origin [Link]

Add the files in the current local repo into the GitHub repo, using git add .

Dept. of CSE, BIT 2024-25 53


Devops
We can commit the added files using git commit -m “Initial commit”

Now push the commit files into the GitHub using git push -u origin master

Dept. of CSE, BIT 2024-25 54


Devops
We can view the uploaded file on our repository

Now, login to Jenkins ([Link] with the username and password created during
Jenkins [Link] on create a New Item and name the new item as GradleApp and select
pipeline, then click OK.

(Creating a New Item)

Dept. of CSE, BIT 2024-25 55


Devops
Select pipeline script from SCM and the source to be Git. Add the GitHub repo URL and select the
Git credentials created during Jenkins configuration. Now click on save.

Now, Click on build now to perform the pipelining.

Running Automated Builds and Tests

Running automated tests and builds is a core part of CI/CD pipelines. In Jenkins we ran such
automated builds and tests using stages defined in the JenkinsFile and integration of Jenkins with
git, enabling it to do following tasks automatically:

1. Checking out source code

2. Building the application

3. Running unit tests

4. Optionally deploying, archiving artifacts, or notifying teams through logs

Dept. of CSE, BIT 2024-25 56


Devops

Program 7:
Configuration Management with Ansible: Basics of Ansible: Inventory,
Playbooks, and Modules, Automating Server Configurations with
Playbooks, Hands-On: Writing and Running a Basic Playbook

Basics of Ansible: Inventory, Playbooks, and Modules

Ansible is an open-source automation tool used for configuration management, application


deployment, and task automation. It allows administrators and DevOps teams to automate IT
infrastructure in a simple, efficient, and human-readable way.

The inventory is a file that defines the hosts (nodes) Ansible will manage.
Playbooks are YAML files that define a series of tasks to be executed on the target systems.
Each playbook consists of one or more plays, which map hosts to tasks.
Modules are units of work in Ansible that execute specific tasks (e.g., installing packages,
copying files, restarting services).
Ansible includes hundreds of built-in modules, and users can create custom modules. Common
modules: apt, yum, copy, service, file, command, shell.

Automating Server Configurations with Playbooks

Ansible Playbooks are the core of automation in Ansible. They enable system administrators and
DevOps engineers to automate server configuration, application deployment, and other IT
tasks in a structured, repeatable, and version-controlled way.

Benefits of Using Playbooks for Server Configuration:

i. Consistency: Ensures all servers are configured in the same way.

ii. Idempotency: Running the playbook multiple times doesn't change the system state if
nothing has changed.

iii. Documentation as Code: Playbooks serve as clear, readable documentation of system


configurations.
iv. Version Control: Playbooks can be stored in Git to track changes and roll back if needed.

Dept. of CSE, BIT 2024-25 57


Devops
Sample Playbook:
- name: Configure Web
Server hosts: webservers
become: yes tasks:
- name: Install Apache
apt:
name: apache2 state:
present
- name: Ensure Apache is running
service:
name: apache2 state:
started enabled:
yes
- name: Deploy custom homepage
copy:
src: [Link]
dest: /var/www/html/[Link]

Writing and Running a Basic Playbook


Ansible inventory and playbook creation on localhost:
Run the update and upgrade commands: sudo apt update && sudo apt upgrade -y

Dept. of CSE, BIT 2024-25 58


Devops
Install ansible through following command: sudo apt install ansible -y

Check the installation and version of ansible: ansible –version

Make a new directory for ansible and go into it: mkdir -p ~/ansible && cd ~/ansible
Open a new file using nano, this is going to be the ansible inventory file: nano [Link]

Type out the following lines and then do Ctrl + O (to write), press Enter then Ctrl + X (to
exit). This successfully creates a [Link] file.

Test Connection to Localhost


Ping the localhost: ansible -i [Link] local -m ping

We get a SUCCESS as an output.

Dept. of CSE, BIT 2024-25 59


Devops
Create an Ansible Playbook
Open a new file using nano, this is going to be the ansible playbook file: nano [Link]
Type out the following lines and then do Ctrl + O, press Enter then Ctrl + X. This
successfully creates a [Link] file.

Run the Ansible Playbook


Run the Ansible Playbook and specify become-pass to ask for a sudo password during
execution: ansible-playbook -i [Link] [Link] --ask-become-pass

Dept. of CSE, BIT 2024-25 60


Devops
Check if Nginx is installed and running and [Link] created
Use system control to check status of NGINX: systemctl status nginx

Display the contents of [Link] created by Ansible: cat /tmp/[Link]

Dept. of CSE, BIT 2024-25 61


Devops

Program 8:
Practical Exercise: Set Up a Jenkins CI Pipeline for a Maven Project, Use
Ansible to Deploy Artifacts Generated by Jenkin
Creating a Maven WebApp

Create a Maven WebApp using the below command:


mvn archetype: generate -DgroupId=[Link] -DartifactId=MavenAnsibleWebApp
-DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

The above command creates a Maven webapp named ‘MavenAnsibleWebApp.’ This


command is like simple maven java application, but here we must change the
DarchetypeArtifactId as -DarchetypeArtifactId=maven-archetype-webapp instead of -
DarchetypeArtifactId=maven- archetype-quickstart, to create a Web Application instead of
Basic Java Application.

Dept. of CSE, BIT 2024-25 62


Devops
Navigate to maven-webapp, and check the file structure using tree command

Have a look at [Link] file. It signifies the presence of a war plugin as the webapp creates a
.war snapshot whereas, the simple java applications create .jar snapshots.

<project xmlns=[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link] [Link]
v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>[Link]</groupId>
<artifactId>maven-webapp</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name> MavenAnsibleWebapp </name>
<url>[Link]
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>MavenAnsibleWebapp</finalName>
<plugins>
<plugin>
<groupId>[Link]</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.2</version> <!-- Updated version -->
</plugin>
</plugins>
</build></project>

Dept. of CSE, BIT 2024-25 63


Devops
Here, The Maven WAR Plugin (maven-war-plugin) is a plugin for Apache Maven that helps
you package a Java web application into a WAR (Web Application Archive) file. WAR files
are used to deploy applications to servlet containers like Apache Tomcat, Jetty, etc.
Now, compile and package the maven webapp using the following command.
mvn clean install – allowing cleaning of directory of any changes made to created App

Now, we can see the presence of .war file in the maven-webapp directory using tree command

Dept. of CSE, BIT 2024-25 64


Devops
Installing Tomcat Server
Use following command to move into root directory: sudo -i
Then, change the directory to /tmp using the command: cd /tmp
Now it is time to download the tomcat webserver tar file use the following wget command:
wget [Link]

Create a directory name ‘tomcat’ in the /opt to download the tomcat-server and navigate to the
same using mkdir and cd commands: mkdir opt/tomcat
Extract the .[Link] file just download into the same directory.

sudo tar -xvzf [Link] -C /opt/tomcat --strip-components=1

We can now list the files and folders within the tomcat folder using ls command.

Dept. of CSE, BIT 2024-25 65


Devops
Now, navigate to conf using cd conf and open the [Link] file.
Here, change the Connector Port Number from 8080 to 9090, since 8080 port number is
already being used in the Jenkins on our system.

Now, open [Link] file and add the user credentials into it, i.e.,
<user username="admin" password="Admin" roles="manager-gui"/

Now go to /opt/tomcat/bin and use ls commands to view its contents:

To run the Apache Tomcat Server, run ‘[Link]’ using sh command

In browser URL, type [Link] and press Enter, we will see Apache Tomcat Server
hosted on our system.
Click on the Manager App button to login using the credentials we updated in the tomcat-
[Link] file i.e., user = admin, password = Admin

Dept. of CSE, BIT 2024-25 66


Devops
We can see the following page:

Writing the Jenkinsfile, Ansible Hosts and Playbook files

Write the Jenkins file by doing gedit Jenkinsfile in our main Maven application directory.
It defines the Maven tools we are using as well as the stages in our execution like: Checkout,
Build, Archive, Deploy.

Dept. of CSE, BIT 2024-25 67


Devops
Now, make a new folder called ansible and create 2 files for ansible deployment called
[Link] and [Link]. Use the commands: mkdir ansible && cd ansible, then gedit
[Link],

followed by gedit [Link]

Create a repository on Github and push the Maven Webapp onto it

Login into Github account and create a repository that is public.

Dept. of CSE, BIT 2024-25 68


Devops
Create a new repository through our terminal to push our Maven Webapp directory to Github.

It prompts for our Github username and password (token):

Successfully pushed all our files onto the repository.


Hosting the Maven Webapp on Tomcat Server through Jenkins
Open a browser and go to [Link] to open Jenkins dashboard.
On the left select the New Item, name the item MavenAnsible-CICD and select item type as
Pipeline.

Dept. of CSE, BIT 2024-25 69


Devops
Now, in Configuration, under Pipeline, select Definition as Pipeline script from SCM, select
SCM as Git.
Enter the repository URL of our Maven Webapp and select Github Credentials.

Specify the branch as */main and then keep everything else as default. Press Save.

Select the MavenAnsible-CICD, and click on Build Now.

Dept. of CSE, BIT 2024-25 70


Devops
In the end, Jenkins Console Output displays this:

When we go to Stage view:

Next, go to [Link] to open Tomcat dashboard. Click on Manager App. Select


our MavenAnsibleWebapp from the table of webapps.
And finally, we get our Hello World output:

Dept. of CSE, BIT 2024-25 71


Devops
Creating a Simple Maven Webapp and Copying Manually
Create a Maven WebApp using the below command:
mvn archetype: generate -DgroupId=[Link] -DartifactId=MavenAnsibleWebapp
-DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false
The above command creates a Maven webapp named ‘MavenAnsibleWebapp.’ This
command is like simple maven java application, but here we must change the
DarchetypeArtifactId as -DarchetypeArtifactId=maven-archetype-webapp instead of -
DarchetypeArtifactId=maven- archetype-quickstart, to create a Web Application instead
of Basic Java Application.
Navigate to maven-webapp, and check the file structure using tree command

Have a look at [Link] file. It signifies the presence of a war plugin as the webapp creates a
.war snapshot whereas, the simple java applications create .jar snapshots.

<project
xmlns=[Link]
xmlns:xsi="[Link]
instance"
xsi:schemaLocation="[Link]
[Link] v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>[Link]</groupId>
<artifactId>maven-webapp</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name> MavenAnsibleWebapp </name>
<url>[Link]
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>

Dept. of CSE, BIT 2024-25 72


Devops
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>MavenAnsibleWebapp</finalName>
<plugins>
<plugin>
<groupId>[Link]</groupId>
<artifactId>maven-war-plugin</artifactId>

<version>3.3.2</version> <!-- Updated version -->


</plugin>
</plugins>
</build>
</project>

Here, The Maven WAR Plugin (maven-war-plugin) is a plugin for Apache Maven that helps
you package a Java web application into a WAR (Web Application Archive) file. WAR files
are used to deploy applications to servlet containers like Apache Tomcat, Jetty, etc.
Contents of [Link] is a default webpage:

Now, compile and package the maven webapp using the following command.

mvn clean install – allowing cleaning of directory of any changes made to created App

Dept. of CSE, BIT 2024-25 73


Devops

Now, we can see the presence of .war file in the maven-webapp directory using tree command

Use cp command to copy the [Link] file from target directory to


/opt/tomcat/webapps, but this needs to be done from root.

Dept. of CSE, BIT 2024-25 74


Devops
So, do sudo -i.

Make sure to start the tomcat service using sudo systemctl start tomcat:

Now, enter [Link] into the browser URL and go to Manager App.

Select our recently made project MavenAnsibleWebapp, and we will get the output:

Dept. of CSE, BIT 2024-25 75


Devops

Program 9:
Introduction to Azure DevOps: Overview of Azure DevOps Services, Setting Up
an Azure DevOps Account and Project

Overview
Azure DevOps offers several key services, each catering to different parts of the software
development lifecycle:

1. Azure Repos: A set of version control tools (Git or Team Foundation Version Control -
TFVC) that enables you to manage your code repositories, track changes, and collaborate with
your team.

2. Azure Pipelines: A continuous integration and continuous delivery (CI/CD) service that
automates the process of building, testing, and deploying code to different environments (e.g.,
development, staging, production).

3. Azure Boards: A tool for agile project management that allows teams to plan, track, and
discuss work. It includes features like Kanban boards, Scrum boards, user stories, and backlog
management.

4. Azure Test Plans: Provides tools for manual and exploratory testing. It helps in tracking
defects and managing test cases to ensure high-quality code.

5. Azure Artifacts: A service that enables teams to host and share packages (like NuGet, npm,
and Maven) within their organization, promoting reuse and easier dependency management.

6. Azure DevOps Services for Collaboration: Features like dashboards, Wikis, and
collaboration tools help teams work together effectively by providing visibility into the status of
projects and workflows.

Dept. of CSE, BIT 2024-25 76


Devops
Steps for creating and setting up Microsoft Azure account
Step 1: Go to the browser and type “[Link]”. Login to Microsoft Azure account.

Step 2: Search for Azure devops organization and click on my azure devops organization. Now it
shows [Link]

Step 3: Click on Create new organization, then click Continue. Enter the organization name and proceed
by clicking Continue.

Dept. of CSE, BIT 2024-25 77


Devops
Step 4: Enter the project name as sampleAzure, select the Private option for project visibility, and
click on Create project. Once created, click on the project sampleAzure.

Step 5: To create a pipeline, click on Pipelines in the left menu and then click Create Pipeline.

Step 6: Choose GitHub. You will be prompted to authorize Azure DevOps to access your GitHub
account.

Dept. of CSE, BIT 2024-25 78


Devops
Step 7: After authorization, all your repositories will be displayed. Select any one repository.

Step 8: Azure will automatically create a basic pipeline YAML script.

Dept. of CSE, BIT 2024-25 79


Devops
Step 9: Go to Project Settings. In the settings menu, click on Agent Pools. Select the Default
agent pool and then click on Agents. You will see that there are currently no agents available
and attempting to run the pipeline will result in a "Permission Denied" error.

Step 10: To set up an agent, click on Download the Agent. After downloading, extract the files
and open the extracted folder.

Dept. of CSE, BIT 2024-25 80


Devops
Step 11: Open your terminal and create a new directory using the command mkdir azureagent,
then navigate to it using cd azureagent.

Step 12: Run the command ls to list the files. You should see files like [Link] and [Link]. And
execute the configuration script using ./[Link].

Step 13: Now, create a PAT for Azure. Go to the Azure DevOps project page, click on User
Settings in the top-right corner, and select Personal Access Tokens.

Dept. of CSE, BIT 2024-25 81


Devops
Step 14 Click on New Token, give it a name like myPAT for devops, set the expiration to No
expiration for 30 days, select Full access, and click Create. Once generated, copy the PAT and
save it securely.

Step 15: Go back to the terminal and paste the PAT when prompted. The agent will now
proceed with registration. Press Enter to select the default agent pool. When prompted for an
agent name and work folder, press Enter to accept the default. The agent is now registered but
still appears offline.

Step 16: Go back to Azure DevOps, open the sampleAzure project, navigate to Project Settings
and then Agent Pools, and you will see the agent ngagana-vm listed as offline

Dept. of CSE, BIT 2024-25 82


Devops

Program 10:
Creating Build Pipelines: Building a Maven/Gradle Project with Azure Pipelines,
Integrating Code Repositories (e.g., GitHub, Azure Repos), Running Unit Tests
and Generating Reports
Steps for creating Maven Project.
Step 1: Create a project named MavenAzurePipeine with private visibility and version control
as Git.

Step 2: Go to the created project and select pipelines.

Step 3: Click on create pipeline and select GitHub(YAML) in connect.

Dept. of CSE, BIT 2024-25 83


Devops
Step 4: Select the repository “nreddyg07/Maven-Jenkins-Pipeline”.

Step 5: Select Maven in configure.

Step 6: Default YAML file is generated. Make necessary changes and click on Run.

Dept. of CSE, BIT 2024-25 84


Devops
[Link] code
trigger:
- master
pool:
name: Default
steps:
- script: echo Myfirst Azure Pipeline for maven project
displayName: 'Run a one-line script'
- script: mvn clean install
displayName: 'Build with
maven'
- script: java -jar target/[Link]
displayName: 'Running jar'

Step 7: Permission needed of the Default agent pool (click on permit).

Step 8: For the job to start running we need to run the agent pool in the terminal.

Step 9: The Job starts to run just after running ./[Link] in the agent directory in the terminal.

Dept. of CSE, BIT 2024-25 85


Devops
Step 10: The job after running successfully.

Step 11: Unit Tests after running successfully.

Step 12: Result shown as succeeded after completion of the job.

Dept. of CSE, BIT 2024-25 86


Devops
Steps for creating Gradle project
Step 1: Create a project named GradleAzurePipeine with private visibility and version control as
Git.

Step 2: Go to the created project and select pipelines.

Step 3: Click on create pipeline and select GitHub(YAML) in connect.

Dept. of CSE, BIT 2024-25 87


Devops
Step 4: Select the repository “nreddyg07/SimpleGradleApp”.

Step 5: Select Gradle in configure.

Step 6: Default YAML file is generated. Make necessary changes and click on Run.

Dept. of CSE, BIT 2024-25 88


Devops
[Link] code
trigger:
- master
pool:
name: Default
steps:
- script: echo My Gradle Application
displayName: 'Run a one-line script'
- script: gradle build
displayName: 'Building the gradle application'
- script: gradle run
displayName: 'Running gradle application'

Step 7: Permission needed of the Default agent pool (click on permit).

Step 8: For the job to start running we need to run the agent pool in the terminal.

Step 9: The Job starts running just after executing ./[Link] in the terminal.

Dept. of CSE, BIT 2024-25 89


Devops
Step 10: The job after running successfully.

Step 11: Unit Tests after running successfully.

Step 12: Result shown as succeeded after completion of the job.

Dept. of CSE, BIT 2024-25 90

You might also like