[go: up one dir, main page]

0% found this document useful (0 votes)
9 views55 pages

Lab Programs

The document provides an overview of DevOps, emphasizing its cultural philosophies and practices aimed at improving collaboration, automation, and efficiency in software development and IT operations. It introduces Maven and Gradle as key build automation tools, detailing their features, installation processes, and differences. Additionally, it covers creating and managing projects with both tools, including dependency management and task automation, and concludes with an introduction to Jenkins for continuous integration and deployment.

Uploaded by

Meghana Prakash
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)
9 views55 pages

Lab Programs

The document provides an overview of DevOps, emphasizing its cultural philosophies and practices aimed at improving collaboration, automation, and efficiency in software development and IT operations. It introduces Maven and Gradle as key build automation tools, detailing their features, installation processes, and differences. Additionally, it covers creating and managing projects with both tools, including dependency management and task automation, and concludes with an introduction to Jenkins for continuous integration and deployment.

Uploaded by

Meghana Prakash
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

Experiment 1: Introduction to Maven and Gradle: Overview of Build Automation

Tools, Key Differences Between Maven and Gradle, Installation and Setup

1. Understanding DevOps
What is DevOps?
DevOps is a set of cultural philosophies, practices, and tools that combine software
development (Dev) and IT operations (Ops). Its goal is to shorten the systems development
life cycle while delivering features, fixes, and updates frequently in close alignment with
business objectives.

DevOps promotes:
• Collaboration: Breaking down silos between development and operations teams.
• Automation: Automating repetitive tasks (builds, tests, deployments) to improve
efficiency.
• Continuous Integration/Delivery (CI/CD): Regularly integrating code changes and
deploying them to production with minimal manual intervention.
• Monitoring and Feedback: Constantly monitoring the performance and behavior of
applications in production to rapidly address issues.

Why is DevOps Used?


• Speed and Agility: Faster development cycles and quicker time-to-market.
• Quality: Automated testing and integration help catch issues early.
• Reliability: Frequent, smaller updates reduce the risk of large-scale failures.
• Efficiency: Automation reduces manual errors and repetitive tasks.
• Scalability: Processes and infrastructure can grow with the business.

Examples of DevOps in Action:


• Continuous Integration (CI): Tools like Jenkins or Azure Pipelines automatically
build and test code on every commit.
• Continuous Deployment (CD): Systems automatically deploy tested code to
production environments.
• Monitoring: Tools such as Prometheus, Grafana, or New Relic continuously monitor
application performance.

2. Introduction to Maven and Gradle


What is Maven?
Maven is a build automation and project management tool primarily used for Java projects. It
uses a central configuration file known as the POM (Project Object Model), written in XML,
which defines the project structure, its dependencies, build order, and plugins.
Key Features and Roles of Maven:
• Convention over Configuration: Maven enforces a standard directory structure (e.g.,
src/main/java, src/test/java), which simplifies project setup.
• Dependency Management: Automatically downloads and manages external libraries
and dependencies from repositories like Maven Central.
• Build Lifecycle: Defines a fixed lifecycle (e.g., compile, test, package, install, deploy)
which standardizes the build process.
• Plugin Ecosystem: Provides a rich set of plugins to extend functionality (e.g., unit
testing, code coverage, reporting).

What is Gradle?
Gradle is a modern build automation tool that is known for its flexibility and performance. It
uses a Groovy or Kotlin DSL (Domain Specific Language) to define build logic, which
allows for more dynamic and customizable configurations compared to Maven’s XML-based
approach.
Key Features and Roles of Gradle:
• Flexible Build Scripts: Instead of a rigid XML file, Gradle build scripts written in Groovy
or Kotlin allow you to include logic, conditionals, and loops.
• Incremental Builds: Gradle tracks changes in source files and only rebuilds what is
necessary, which can significantly speed up the build process.
• Multi-project Builds: Easily manages complex projects with multiple modules or
subprojects.
• Extensibility: A robust plugin system that enables you to integrate various languages,
frameworks, and tools.
• Parallel Execution: Can run tasks in parallel, optimizing build times for large projects.
3. Why Use Maven and Gradle?
Both Maven and Gradle are used to automate the build process and manage project
dependencies. Here’s why they are so popular in the DevOps ecosystem:
• Automated Build and Testing: They allow developers to compile code, run tests, and
package applications without manual intervention.
• Consistent Build Environment: By enforcing standardized project structures and
dependency management, they help avoid the “it works on my machine” problem.
• Ease of Integration: Both tools integrate well with Continuous Integration (CI) servers like
Jenkins, enabling automated pipelines.
• Dependency Resolution: They simplify the process of managing external libraries and
ensure that all developers are using the same versions.
4. Differences between Maven and Gradle
JDK Installation Steps:

1) Download jdk using wget in the terminal


wget
https://github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.1+12/OpenJDK
17U-jdk_x64_linux_hotspot_17.0.1_12.tar.gz
2) Create a local directory to store the JDK (if it doesn't exist):
mkdir -p ~/local

3) Extract the JDK archive to your local directory:


tar -xvzf OpenJDK17U-jdk_x64_linux_hotspot_17.0.1_12.tar.gz -C ~/local

4) Edit your (.bashrc) to set Set up environment variables


nano ~/.bashrc

5) Add the following lines to the end of the file:


# Set JAVA_HOME and PATH for OpenJDK
export JAVA_HOME=~/local/jdk-17.0.1+12
export PATH=$JAVA_HOME/bin:$PATH

6) In nano, press Ctrl + O to save and Ctrl + X to exit.

7) After editing .bashrc, you need to apply the changes to your current terminal session:
source ~/.bashrc

8) Check the Java version: java -version


You should see output similar to:
openjdk version "17.0.1" 2021-10-19
OpenJDK Runtime Environment (build 17.0.1+12-39)
OpenJDK 64-Bit Server VM (build 17.0.1+12-39, mixed mode)
INSTALLATION OF MAVEN

1) DOWNLOAD MAVEN USING wget in the terminal


wget
https://downloads.apache.org/maven/maven-3/3.9.5/binaries/apache-maven-3.9.5-bin.tar.gz

2) EXTRACT THE TAR FILE


tar -xvzf apache-maven-3.9.5-bin.tar.gz -C ~/

3) Rename the Extracted Folder:


mv ~/apache-maven-3.9.5 ~/maven

4) Add Maven to PATH:


echo export PATH=$PATH:~/maven/bin >> ~/.bashrc

5) Apply the Changes:


source ~/.bashrc

6) Verify the Installation:


mvn -version
INSTALLATION OF GRADLE

1) DOWNLOAD GRADLE USING wget in the terminal


wget https://services.gradle.org/distributions/gradle-8.4-bin.zip

2) EXTRACT THE TAR FILE


unzip gradle-8.4-bin.zip -d ~/

3) Rename the Extracted Folder:


mv ~/gradle-8.4 ~/gradle

4) Add Gradle to PATH:


echo export PATH=$PATH:~/gradle/bin>> ~/.bashrc

5) Apply the Changes:


source ~/.bashrc

6) Verify the Installation:


gradle -v
Experiment 2: Working with Maven: Creating a Maven Project, Understanding the
POM File, Dependency Management and Plugins
1. Introduction to Maven

Maven is a powerful build automation and project management tool primarily used for Java
projects. It simplifies the build process by:
• Enforcing a standard project structure (convention over configuration).
• Managing dependencies automatically by downloading them from remote repositories
(e.g., Maven Central).
• Defining a clear build lifecycle (compile, test, package, install, deploy).
• Allowing the integration of various plugins to extend functionality (e.g., testing,
reporting).

2. Basic Structure of POM File:


<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>hello-world</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>hello-world</name>
<url>http://maven.apache.org</url>
<dependencies>
​ <dependency>
​ <groupId>junit</groupId>
​ <artifactId>junit</artifactId>
​ <version>3.8.1</version>
​ <scope>test</scope>
​ </dependency>
</dependencies>
</project>

3. Dependency Management with Maven

How Maven Manages Dependencies:

• Automatic Download: When you specify a dependency in the <dependencies>


section, Maven automatically downloads the library from a remote repository (usually
Maven Central).
• Transitive Dependencies: Maven also resolves dependencies required by your
dependencies.
• Version Control: You can specify precise versions for each dependency, ensuring
consistency across builds.

<dependencies>
​ <dependency>
​ <groupId>junit</groupId>
​ <artifactId>junit</artifactId>
​ <version>3.8.1</version>
​ <scope>test</scope>
​ </dependency>
</dependencies>
●​ groupId, artifactId, version: These three elements uniquely identify the dependency.
●​ scope: The test scope ensures that this dependency is only available during the test
phase and not included in the final artifact.
4. Maven Plugins: Extending Maven Functionality
Plugins are key to Maven’s flexibility, adding tasks to your build process.
This plugin is used to compile your Java source code.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
• Configuration: Specifies that the project should be compiled using Java 11.

5. Building and Testing Your Maven Project​ ​ ​ ​


Open your terminal and navigate to the directory where you want to create your
MAVEN project.

1. Create a New Maven Project

mvn archetype:generate -DgroupId=com.example -DartifactId=hello-world


-DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

○​ -DgroupId=com.example: This is the group ID of your project (usually your


domain or organization).​
​ ​
○​ -DartifactId=hello-world: This is the name of your project.​
​ ​
○​ -DarchetypeArtifactId=maven-archetype-quickstart: This uses the quickstart
template for a simple Java project.​
​ ​
○​ -DinteractiveMode=false: This skips interactive prompts during project
creation.​
​ ​
○​ This will generate a directory named hello-world with the Maven project
structure.​

2. Navigate to the Project Directory

cd hello-world
3. Check the Project Structure

hello-world/

├── pom.xml

└── src/

​ └── main/

​ └── java/

​ └── com/

​ └── example/

​ └── App.java

The key files here are:

●​ pom.xml: The Maven project descriptor file, where dependencies and ​


configurations are defined.​

●​ src/main/java/com/example/App.java: The main Java class that prints "Hello
World".

4. Modify the Java Code (Optional)

You can modify src/main/java/com/example/App.java to customize the output. The code


should look like this:

package com.example;

public class App {

​ public static void main(String[] args) {

​ System.out.println("Hello, Maven World!");

​ }


5. Build the Project with Maven

To build and compile the project, run the following command in the hello-world directory:

mvn package

6. Run the Project

java -cp target/hello-world-1.0-SNAPSHOT.jar com.example.App

This should print:

Hello, Maven World!​

7. Clean the Project

If you want to clean up the build artifacts, run:

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

1. Introduction to Gradle

Gradle is a modern build automation tool designed to be highly flexible, fast, and scalable. It
is widely used in Java projects, Android development, and many multi-language projects.

Here’s what makes Gradle stand out:

• Flexible Build Scripts: Gradle uses a Domain Specific Language (DSL) based on either
Groovy (by default) or Kotlin. This provides a more dynamic and expressive way to define
build logic compared to static XML configurations (as used in Maven).

• Incremental Builds: Gradle optimizes build times by determining what parts of the project
have changed and rebuilding only those parts.

• Task Automation: Everything in Gradle is treated as a task, allowing you to create custom
tasks or reuse existing ones for compiling code, running tests, packaging, and more.

• Dependency Management: Like Maven, Gradle can automatically download and manage
dependencies from remote repositories (e.g., Maven Central, JCenter, or custom repositories).

Open your terminal and navigate to the directory where you want to create your Gradle
project.

1. Create a New directory for GRADLE Project


mkdir hello-world-gradle

2. Navigate to the Project Directory

cd hello-world-gradle

3.Initialize a Gradle project using the following command:


gradle init --type java-application

4. Check the Project Structure


hello-world-gradle/
├── build.gradle
├── settings.gradle
└── src/
​ └── main/
​ └── java/
​ └── hello/
​ └── App.java

5. Modify the Java Code (Optional)


The generated App.java file is located at src/main/java/hello/App.java. By default, it
will look like this:

package hello;

public class App {


​ public static void main(String[] args) {
​ System.out.println("Hello, Gradle World!");
​ }
}

6. Build the Project with GRADLE


To build and compile the project, run the following command in the hello-world-gradle
directory:
gradle build

This will:

●​ Compile your Java files


●​ Download any required dependencies (if specified)
●​ Package the project into a .jar file.

Gradle will create a build/ directory containing the compiled files.

6. Run the Project


gradle run

This should print:


Hello, Gradle World!

7. Clean the Project


If you want to clean up the build artifacts, run:
gradle clean
2. Explanation of Components:

• build.gradle:
This is the main build script written in Groovy (or Kotlin if you choose). It defines plugins,
repositories, dependencies, and tasks.

• settings.gradle:
A small script that defines the project’s name and, in multi-project builds, the included
subprojects.

• gradlew / gradlew.bat:
The Gradle wrapper scripts. They allow you to run Gradle without requiring a separate
installation on every machine by automatically downloading the correct gradle version.

• src/main/java:
Contains your application’s source code.

• src/test/java:
Contains your unit tests.

3. Dependency Management in Gradle

How It Works:
• Repositories: Gradle downloads dependencies from defined repositories (e.g., Maven
Central).
• Dependency Notation: Dependencies are defined in a simple format: group:artifact:version.
• Configuration Types: Gradle provides various configurations such as implementation,
compileOnly, runtimeOnly, and testImplementation to manage the scope of each dependency.

Example:

In our build script examples, we included JUnit for testing:


dependencies
{
testImplementation 'junit:junit:4.13.2'
}

This line tells Gradle to download JUnit version 4.13.2 from Maven Central and include it in
the test classpath.
4. Task Automation in Gradle

In Gradle, nearly everything is a task. Tasks represent individual units of work (compiling
code, running tests, packaging applications). Gradle comes with many built-in tasks
(provided by plugins) and allows you to define your own custom tasks.
Built-in Tasks:
• compileJava: Compiles the source code in src/main/java.
• test: Runs tests in src/test/java.
• jar: Packages compiled code into a JAR file.
• run: Runs the application (if the application plugin is applied).
Experiment 4: Introduction to Jenkins: What is Jenkins?, Installing Jenkins on Local or
Cloud Environment, Configuring Jenkins for First Use

1. What Is Jenkins?

Definition and Overview


Jenkins is an open-source automation server written in Java. It is widely used to facilitate
Continuous Integration (CI) and Continuous Deployment/Delivery (CD) pipelines in software
development. Jenkins automates repetitive tasks related to building, testing, and deploying
software, helping teams to integrate changes continuously and deliver high-quality
applications faster.

Key Functionalities

• Continuous Integration/Delivery: Automatically builds, tests, and deploys code after each
commit.
• Extensible Plugin Ecosystem: Over 1,500 plugins allow integration with numerous tools
such as Git, Maven, Gradle, Docker, and many cloud providers.
• Automated Builds: Jenkins can poll version control systems, trigger builds on code changes,
and even schedule builds.
• Pipeline as Code: With the introduction of Jenkins Pipeline (using either scripted or
declarative syntax), you can define your entire build process in a code file (Jenkinsfile) and
store it alongside your code.
• Distributed Builds: Jenkins can distribute workloads across multiple machines, helping to
run tests and builds faster.
• Monitoring and Reporting: Provides detailed logs, test reports, and build history.

Why Use Jenkins?

• Improved Efficiency: Automates mundane tasks to free up developer time.


• Rapid Feedback: Quickly identifies integration issues with automated tests.
• Scalability: Supports distributed builds and parallel testing.
• Customization: A highly configurable system that can integrate with nearly every tool in the
software development lifecycle.
2. Installation of Jenkins

1) Download jenkins using wget in the terminal


wget https://get.jenkins.io/war-stable/latest/jenkins.war -P ~/local/jenkins

2) Create a Directory for Jenkins


mkdir -p ~/local/jenkins

3) Ensure the downloaded jenkins.war file is in the directory: mv jenkins.war ~/local/jenkins/

4) Run Jenkins
cd ~/local/jenkins

5) Optional
gedit /home/student/.jenkins/config.xml
(DisableSignup must be made False)

5) Run Jenkins with the following command:


java -jar jenkins.war --httpPort=8080

6) Access Jenkins
1. Open a web browser and go to http://localhost:8080
2. The first time Jenkins runs, you will be asked for an unlock key. You can find the key in
the terminal where Jenkins is running.
Look for a line that says:
Unlock Jenkins at http://localhost:8080
Please wait while Jenkins is getting ready to work...
Jenkins is fully up and running. Unlock it by accessing the following URL from your
browser:
http://localhost:8080
In the terminal output, you will be able to see the below message
*************************************************************
*************************************************************
Jenkins is fully up and running
Please wait while Jenkins is getting ready to work...
Unlock Jenkins at http://localhost:8080
*************************************************************
*************************************************************

7) The unlock key is typically found in the Jenkins log or in the following location in
your user directory:
cat ~/.jenkins/secrets/initialAdminPassword
Experiment 5: Build and Run a Java Application with Maven, Migrate the Same
Application to Gradle.

​ ​ ​ ​
Part A: Build and Run a Java Application with Maven

1. Create the Maven Project

​ Open your Terminal.

2. Generate the Maven Project using the Quickstart Archetype

Type the following command and press Enter:

mvn archetype:generate -DgroupId=com.example -DartifactId=HelloMaven


-DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

a. What it does:

This command creates a new Maven project with the group ID com.example and the artifact
ID HelloMaven. The archetype sets up a basic Java application, including a sample test.

b. Expected Output:

Maven will display messages as it downloads dependencies and generates the project files.

3. Change Directory into the Newly Created Project:

cd HelloMaven

Explore the Maven Project Structure

Your project directory should have a structure similar to this:

HelloMaven/

├── pom.xml

└── src

├── main

│ └── java

│ └── com

│ └── example

│ └── App.java

└── test
└── java

└── com

└── example

└── App.java

●​ pom.xml: The Maven configuration file (POM) that defines your ​ project’s
coordinates, dependencies, and plugins.​

●​ src/main/java: Contains your application’s source code.​

●​ src/test/java: Contains unit tests.​

4. Build the Maven Project

1. Compile and Package the Application:

mvn package

a. What it does:

This command compiles the source code, runs tests, and packages your application into
a JAR file (located in the target directory).

b. Expected Output:

You should see a “BUILD SUCCESS” message along with information on the

created JAR file.

5. Run the Maven Application

1. Run the Application Using the JAR File:

Execute the following command:

java -cp target/HelloMaven-1.0-SNAPSHOT.jar com.example.App

a. What it does:

This command runs the com.example.App class from the JAR file generated

in the previous step.

b. Expected Output:
The output should display:

Hello World!

(This is the default message printed by the generated App.java.)

To change the output, change print statement to Hello Maven, so that you will get to
know that Maven project migrates to Gradle when gradle is executed.

Part B: Migrate the Application to Gradle

In this part, you will create a Gradle project that contains the same Java application code,
then build and run it using Gradle.

1. Create a New Gradle Project

Open a New Terminal Window or Navigate Back to Your Workspace.

2. Create a New Directory for the Gradle Project:

mkdir HelloMavenGradle

cd HelloMavenGradle

a. What it does:

Creates and navigates into a folder named HelloMavenGradle for your new Gradle project.

3. Initialize the Gradle Project Using the Java Application Type:

gradle init --type java-application

a. What it does:

Gradle will generate a basic Java application project with a default project

structure.

b. Expected Output:

You will see interactive prompts or a confirmation message stating that the

project has been generated.


4. Adjust the Gradle Project to Use the Same Code

The Gradle project structure will look similar to this:

HelloMavenGradle/

├── build.gradle

├── settings.gradle

└── src

├── main

│ └── java

│ └── App.java

└── test

└── java

└── App.java

5. The Project name and Source Package must be as follows:

Project name (default: HelloGradle): com.example

Source package (default: com.example): com.example

6. Copy Java Code from Maven

mv ~/Desktop/HelloMaven/src/main/java/com/example/App.java
~/Desktop/HelloGradle/app/src/main/java/com/example/​

7. Update Gradle Build File (ignore if main class is already same as below)

Open build.gradle.kts and set the main class(search file in gradle)

plugins {

id 'application'

repositories {

mavenCentral()

}

application {

mainClass = 'com.example.App'

8. Gradle App.java must contain below code:

package com.example;

/**

* Hello world!

*/

public class App

public static void main( String[] args )

System.out.println(new App().getGreeting());

public String getGreeting() {

return "Hello, Maven!";

9. Build & Run with Gradle

gradle build
10. Run the application

gradle run

OUTPUT:

Hello Maven​


EXTRA PROGRAM: Create a simple in Java that takes two numbers as input,
adds them, and displays the result. The project should follow the standard
Maven structure and use JUnit for testing.
package com.example;
import java.util.Scanner;

public class App


{

​ public static int add(int a,int b){


​ ​ return a+b;
​ }
public static void main( String[] args )
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter no 1 :");
int n1=sc.nextInt();
System.out.println("Enter no 2 :");
int n2=sc.nextInt();
System.out.println("Sum of "+n1+" and "+n2+" : "+new App().add(n1,n2));
}
}

OUTPUT:


EXTRA PROGRAM: Develop a basic in Java that accepts two numbers as
input, performs mathematical operations(+, -, /, *), and displays the result. The
project should adhere to the standard Gradle directory structure and
incorporate .

package com.example;
import java.util.Scanner;
public class App {
public String getGreeting() {
return "Calculator";
}
public static void main(String[] args) {
System.out.println(new App().getGreeting());
Scanner sc = new Scanner(System.in);
int choice,result;
while (true) {
System.out.println("1. Addition \n2. Subtraction\n3. Multiplication\n4.
Division\n5. Exit\nEnter your choice: ");
choice = sc.nextInt();
if (choice==5) {
System.out.println("Exiting...");
System.exit(0);
}
if (choice<1 || choice>4) {
System.out.println("Invalid choice! Please enter a valid option.");
continue;
}
System.out.print("Enter num 1: ");
int n1=sc.nextInt();
System.out.print("Enter num 2: ");
int n2=sc.nextInt();
switch (choice) {
case 1:
result = n1+n2;
System.out.println("Result : "+result);
break;
case 2:
result = n1-n2;
System.out.println("Result : "+result);
break;
case 3:
result = n1*n2;
System.out.println("Result : "+result);
break;
case 4:
if (n2==0) {
System.out.println("Error! Division by zero is not allowed.");
} else {
result = n1/n2;
System.out.println("Result : "+result);
}
break;
}
}
}
}


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

What is a CI Pipeline?
A Continuous Integration (CI) Pipeline automates the process of building, testing,
and integrating code changes every time code is committed to the repository. This
pipeline:
• Automatically checks out the latest code.
• Compiles the application.
• Runs tests to catch errors early.
• Notifies the team of build/test results.

Why Use Jenkins for CI?


• Automation: Jenkins automates the build and test cycle, reducing manual
intervention.
• Immediate Feedback: Developers get rapid notifications of any integration issues.
• Extensibility: With hundreds of plugins available, Jenkins can integrate with version
control systems, build tools (Maven, Gradle), testing frameworks, and more.
• Pipeline as Code: Using Jenkins Pipelines (defined in a Jenkinsfile), you can
manage the CI process as part of your source code repository.

Step 1: Create Hello-world Maven project in desktop,than follow the below


steps:

●​ mvn archetype:generate -DgroupId=com.example -DartifactId=hello-world


-DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
●​ cd hello-world
●​ Build the project using mvn package
●​ Run using java -cp target/hello-world-1.0-SNAPSHOT.jar com.example.App
●​ Run cmd mvn test for test reports

(ALERT : Verify Git version using git --version)

Step 2: Start Jenkins(Open new terminal)


cd local
cd jenkins
●​ Run this cmd in terminal to start jenkins : java -jar jenkins.war --httpPort=8080
●​ Start Jenkins and open your browser.​

●​ Go to http://localhost:8080 (or your Jenkins server URL).​

●​ Log in using your admin username and password( Check your observation book
for Jenkins username and password)

Step 3: Create Github account

●​ Create new repository (Maven-CI)


●​ Click on create repository

Step 4: Create a New Jenkins Job

1.​ On the Jenkins Dashboard, click "New Item".​

2.​ Enter a name for the job, e.g., Maven-CI.​

3.​ Select "Freestyle project" and click OK.

Step 5: In Terminal initiate git to push the local file to git

●​ Navigate to Maven Project


●​ Initaite git : git init
●​ Add Files: git add . (Include the dot)
●​ Authenticate the git Acc using mail : git config --global user.email “yourmailid”
●​ Authenticate the git Acc using username : git config --global user.name
“yourusername”
●​ Create a new commit with the staged changes and assign it a message "First
commit". : git commit -m “First commit”
●​ Add a remote repository named origin that links it to your local Git repository.:
git remote add origin https://github.com/YourUserName/RepoProjectName.git
●​ Rename the current branch to MAIN: git branch -M main
●​ Go to Github to create Tokens:
❖​ Profile >> Settings >> Developers Settings >> Personal Access Tokens
>> Tokens(classic) >> Generate New Token(classic) >> Given Token
name >> Click on repo >>Click Generate >> Copy and keep it safely
●​ Push your local main branch to the remote repository and sets it as the upstream
branch git push -u origin main
●​ Give the required credentials
●​ Check weather the files are pushed into the Git Repo

Step 6: Configuration

1.​ In the job configuration page, scroll down to "Source Code Management".​

2.​ Select "Git" (if using Git for version control).​

3.​ Enter the Repository URL,

e.g.: (https://github.com/yourusername/your-maven-project.git)

4.​ Under Branches to build, enter: (*/main)


5.​ Under Build steps, add build steps as: Invoke Top-Level Maven Targets
●​ In Goals, type clean package

6. Under Post Build Action, add as: “Publish JUnit test result report”.

7. Test Report XMLs: In the field, enter the pattern that matches your test report

files. **/target/surefire-reports/*.xml

Step 7: Save and Run the Job

1. Save the Configuration:

●​ Click “Save” at the bottom of the job configuration page.

2. Trigger a Build:

●​ On the job’s main page, click “Build Now”.


●​ The build will be added to the build history on the left side.
3. Monitor Build Output:

●​ Click on the build number (e.g., #1) and then click “Console Output”.

Verify that Jenkins successfully checks out the code, runs the build commands

and executes tests.

●​ Look for “BUILD SUCCESS” or the equivalent output to confirm that the

build and tests passed.

Step 8. Setting Up a CI Pipeline with Jenkins (Pipeline as Code)

For greater flexibility and version-controlled CI configuration, you can use a Jenkins Pipeline

defined in a Jenkinsfile.

Create a Pipeline Job

1. Log into Jenkins and click on “New Item”.

2. Enter an Item Name: For example, Pipeline-CI.

3. Select “Pipeline” and click “OK”.

Step 9: Define the Pipeline Script

1. Configure the Pipeline:

●​ In the job configuration page, scroll to the “Pipeline” section.


●​ Choose “Pipeline script” (or “Pipeline script from SCM” if you want to load the script
from your repository).

2. Enter the Pipeline Script:(on 8th line, enter your git url)

Below are sample pipeline scripts for Maven and Gradle projects.

Example for a Maven Project:

pipeline {

​ agent any
​ stages {

​ stage('Checkout') {

​ steps {

​ // Explicitly checkout code from a Git repository

​ git url: 'https://github.com/yourusername/projectname.git', branch:


'main'

​ }

​ }

​ stage('Build') {

steps {

// Run Maven build

sh 'mvn clean package'

stage('Test') {

steps {

// Optionally, separate test execution if needed

sh 'mvn test'

​ stage('Compile') {

​ steps {

​ // Compile the Java program using javac

​ sh 'javac src/main/java/com/example/App.java'

​ }

​ }
​ stage('Run') {

​ steps {

​ // Run the Java program using the java command with the fully qualified
class name

​ sh 'java -cp src/main/java com.example.App'

​ }

​ }

​ }

​ post {

​ always {

​ echo 'Cleaning up resources or sending notifications.'

​ }

​ }

3. Save the Pipeline Script:

●​ After entering your pipeline script, click “Save”.

Step 10: Run the Pipeline

1. Trigger the Build:

●​ On the Pipeline job’s main page, click “Build Now”.


●​ Monitor the build progress through the Pipeline visualization or by clicking on the
build number and then “Console Output”.

2. Verify the Results:

●​ Confirm that each stage (Checkout, Build, Test) executes successfully.


●​ Review the archived test reports to verify that tests have run and passed.




Experiment 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

What Is Ansible?

Ansible is an open-source IT automation and configuration management tool. It


allows you to manage multiple servers and perform tasks such as:

• Configuration Management: Automate the configuration of servers.

• Application Deployment: Deploy applications consistently.

• Orchestration: Coordinate complex IT workflows and processes.

Key Concepts in Ansible

• Inventory:

An inventory is a file (usually in INI or YAML format) that lists the hosts (or groups

of hosts) you want to manage. It tells Ansible which machines to target.

• Playbook:

A playbook is a YAML file that defines a set of tasks to be executed on your target

hosts. It is the heart of Ansible automation. In a playbook, you specify:

o Hosts: The target machines (or groups) on which the tasks should run.

o Tasks: A list of actions (using modules) that should be executed.

o Modules: Reusable, standalone scripts that perform specific actions (e.g.,

installing packages, copying files, configuring services).

• Modules:

Ansible comes with a large collection of built-in modules (such as apt, yum, copy,

service, etc.). These modules perform specific tasks on target hosts. You can also

write custom modules if needed.


Why use Ansible?

Agentless: Ansible uses SSH to communicate with target hosts, so no agent needs
to be installed on them.

• Simplicity: Playbooks use simple YAML syntax, making them easy to write and
understand.

• Idempotence: Ansible tasks are idempotent, meaning running the same playbook
multiple times yields the same result, ensuring consistency.

• Scalability: Ansible can manage a small number of servers to large infrastructures


with hundreds or thousands of nodes.

Step 1: Create the Playbook File

1.​ Check for ansible version: ansible --version


2.​ Open your text editor to create the playbook file: Open your terminal and
type the following to create the setup.yml file using nano:

gedit setup.yml (Yet Another Markup Language)


3. Add the following YAML content: Copy and paste this content into the
setup.yml file you just opened:

---
- name: Basic Server Setup (Without Sudo)
hosts: local
tasks:
​ - name: Create a directory for development
​ file:
​ path: "{{ ansible_env.HOME }}/dev"
​ state: directory
​ mode: '0755'

​ - name: Create a text file with content


​ copy:
​ content: |
​ This is a test file created by Ansible.
​ dest: "{{ ansible_env.HOME }}/test_file.txt"
​ mode: '0644'
Step 2: gedit hosts.ini (Inventory File Format)

Step 2: Run the Playbook

Now that you have the playbook, you can run it using the ansible-playbook
command. Here's how to run it:

ansible-playbook -i hosts.ini setup.yml


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

In this experiment, you will:

• Set up a Jenkins job to automatically build a Maven project from source control.

• Archive the build artifact (a JAR file) produced by Maven.

• Integrate an Ansible deployment step within Jenkins (using a post-build action) to


deploy the artifact to a target location.

• Verify that the artifact is deployed successfully.

This exercise demonstrates how Continuous Integration (CI) and automated


configuration management can work together to streamline the build-and-deploy
process.​

1. Prerequisites

Before you begin, ensure that:

• Jenkins is installed, running, and accessible (locally or on the cloud).

• Maven Project: You have a Maven project available in a Git repository (or stored

locally). For this example, we will assume you are using the “HelloMaven” project
generated in Experiment 2/4.

• Git Repository: The Maven project is committed to a Git repository (e.g., on GitHub)
so Jenkins can pull the latest code.

• Ansible Installed: Ansible is installed on your control machine (or the Jenkins
server) and you have created a basic inventory file (e.g., hosts.ini)

Step 1: Create Hello-world Maven project in desktop,than follow the below


steps:

a)​ mvn archetype:generate -DgroupId=com.example -DartifactId=hello-world


-DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
b)​ cd hello-world
c)​ Build the project using mvn package
d)​ Run using java -cp target/hello-world-1.0-SNAPSHOT.jar com.example.App
e)​ Run cmd mvn test for test reports

(ALERT : Verify Git version using git --version)


Step 2: Start Jenkins
●​ Run this cmd in terminal to start jenkins : java -jar jenkins.war --httpPort=8080

●​ Go to http://localhost:8080 (or your Jenkins server URL).​

●​ Log in using your admin username and password.


Step 3: Create Github account

●​ Create new repository (Maven-CI)


●​ Click on create repository

Step 4: Create a New Jenkins Job

1.​ On the Jenkins Dashboard, click "New Item".​

2.​ Enter a name for the job, e.g., Maven-CI.​

3.​ Select "Freestyle project" and click OK.

Step 5: In Terminal initiate git to push the local file to git

●​ Navigate to Maven Project


●​ Initaite git : git init
●​ Add Files: git add .
●​ Authenticate the git Acc using mail : git config --global user.email “yourmailid”
●​ Authenticate the git Acc using username : git config --global user.name
“yourusername”
●​ Create a new commit with the staged changes and assign it a message "First
commit". : git commit -m “First Commit”
●​ Add a remote repository named origin that links it to your local Git repository.:
git remote add origin https://github.com/YourUserName/RepoProjectName.git
●​ Rename the current branch to MAIN: git branch -M main
●​ Go to Github to create Tokens:
❖​ Profile >> Settings >> Developers Settings >> Personal Access Tokens
>> Tokens(classic) >> Generate New Token(classic) >> Given Token
name >> Click on repo >>Click Generate >> Copy and keep it safely
●​ Push your local main branch to the remote repository and sets it as the upstream
branch git push -u origin main
●​ Give the required credentials
●​ Check weather the files are pushed into the Git Repo

Step 6 :Create hosts file

1.​ Open your text editor to create the playbook file: Open your terminal and
type the following to create the hosts.ini file using gedit:

gedit hosts.ini

2.​ Add the following content:

[local]
localhost ansible_connection=local

Step 7 :Create deploy file

1.​ Open your text editor to create the playbook file: Open your
terminal and type the following to create the deploy.yml file using
gedit:

gedit deploy.yml

2. Add the following content:(Src: project file(hello-maven)→target→jar


file path, dest: jenkins→create deploy folder→copy folder name with
project name)
---
- name: Deploy Maven Artifact
hosts: localhost
connection: local
gather_facts: no

tasks:
​ - name: Copy the artifact to the deployment directory
​ copy:
​ src:
"/home/student/Desktop/hello-world/target/hello-world-1.0-SNAPSHOT.ja
r"
​ dest: "/home/student/local/jenkins/deploy/hello-world.jar"
Create folder name: deploy in local/jenkins

Step 8: Configuration

1.​ In the job configuration page, scroll down to "Source Code Management".​

2.​ Select "Git" (if using Git for version control).​

3.​ Enter the Repository URL, e.g.:


(https://github.com/yourusername/your-maven-project.git)​

4.​ Under Branches to build, enter: (*/main)


5.​ Under Build steps, add build steps as: Invoke Top-Level Maven Targets
●​ In Goals, type clean package
1. Add Another Post-build Action:
●​ Click “Add build step” and select “Execute shell”.
2. Configure the Shell Command:
●​ In the command box, add a command to trigger your Ansible
playbook.

ansible-playbook -i /path/to/hosts.ini /path/to/deploy.yml


( Note:

Replace /path/to/hosts.ini with the full path to your Ansible
inventory file.

Replace /path/to/deploy.yml with the full path to your Ansible
deployment playbook.)
3. Save the Jenkins Job:
●​ Click “Save” at the bottom of the configuration page.

Step 9: Run the Jenkins:

1. Trigger a Build in Jenkins:


●​ Navigate to your Jenkins job (HelloMaven-CI) and click
“Build Now”.
●​ Monitor the build history. Once the build completes, click
the build number
●​ (e.g., #1) and check the Console Output.

2. Verify Deployment:
●​ Log into your target machine (or check locally) and
verify that the artifact has been copied to the
destination
directory(e.g.,/opt/deployment/HelloMaven.jar)


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

( BEFORE STARTING THE EXPERIMENT MAKE SURE YOU HAVE MICROSOFT ACC )
Step 1: Sign Up for an Azure DevOps Account
1. Open Your Web Browser:

●​ Navigate to the Azure DevOps website:


https://azure.microsoft.com/en-us/products/devops/

2. Click on Sign In:

Step 2: Create an Azure DevOps Organization


1. Create a New Organization:
●​ Once signed in, you will be prompted to create an Azure DevOps organization.
●​ In Search Tab, search for Azure DevOps Organization

●​
●​ Click on My Azure DevOps Organizations
●​ Enter a unique name for your organization (e.g., YourCompanyDevOps or
MyPersonalOrg).
●​ Select a Region,Enter the characters you see in Captcha
●​ Click “Create”.

2. Review Your Organization’s Dashboard:


●​ Once created, you will see an overview dashboard for your organization. This
dashboard provides navigation links to Repos, Pipelines, Boards, Test Plans, and
Artifacts.

Step 3: Creating an Azure DevOps Project

1. Navigate to “New Project”:


●​ On your organization’s dashboard, click the “New Project” button.

2. Configure Your Project:


●​ Project Name: Enter a descriptive name for your project (e.g., HelloDevOps).
●​ Description: Optionally, provide a brief description (e.g., “A sample project to
demonstrate Azure DevOps services”).
●​ Visibility:
➢​ Choose “Private” if you want to restrict access to your project.
●​ Click “Create”.

3. Explore Your Project Dashboard


●​ Project Overview:
Once your project is created, you will be directed to the project dashboard. Here
you will see navigation options for:
➢​ Repos: Where your code is stored.
➢​ Pipelines: For build and release automation.
➢​ Boards: For work tracking and agile planning.
➢​ Test Plans: For managing and running tests.
➢​ Artifacts: For hosting packages.


Experiment 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

Step 1: Create or Use a Maven Project


Step 2: Create the git repo and Push Your Code to GitHub

Step 3: Create Azure DevOps Project

1.​ Go to https://dev.azure.com.​

2.​ Click New Project → Enter name → Set visibility → Create.

Step 4: Connect Your GitHub Repo

1.​ Go to your project in Azure DevOps.​

2.​ Navigate to Pipelines > Create Pipeline.​

3.​ Select GitHub.​

4.​ Authorize access if needed and select your repository.


5.​ Select Maven to Configure your pipeline​

6.​ Save it but Don’t Run it.

Step 5: Create a Personal Access Token (PAT) in Azure DevOps

●​ Go to your Azure DevOps portal.​

●​ Click on your profile icon (top right) → Security.​

●​ Click Personal Access Token​

●​ Fill in:​

○​ Name: self-hosted-agent​

○​ Organization: your Azure DevOps org​

○​ Scopes:​
Click Full Access
○​ Click Create and copy the token. Keep it safe for now — you’ll use
it during configuration.

Step 6: Create a Self-hosted Agent in Azure DevOps

○​ Open a terminal and run:

○​ # Create a directory for the agent


○​ mkdir myagent && cd myagent

○​ # Download the latest agent package


○​ wget
https://vstsagentpackage.azureedge.net/agent/3.236.1/vsts-agent-l
inux-x64-3.236.1.tar.gz

○​ # Extract it
○​ tar zxvf vsts-agent-linux-x64-3.236.1.tar.gz

○​ # Run configuration
○​ ./config.sh

Step 7: Enter the details as asked:

●​ Server URL: https://dev.azure.com/YOUR_ORG_NAME​

●​ Authentication Type: PAT​

●​ Paste your PAT when asked​

●​ Agent pool: Default (or the one you created)​


●​ Agent name: any name, e.g., mylinuxagent​

●​ Accept all defaults for now.

Step 8: Run the Agent

●​ Run the code in terminal : ./run.sh

●​ Leave this terminal window open — the agent is now listening for jobs!

Step 9: Run Your Pipeline

Now go back to Azure DevOps:

●​ Go to Pipelines​

●​ Click your pipeline


●​ Click on Edit
●​ Change : pool: vmImage: 'ubuntu-latest' to

pool:

name: Default

●​ Change : jdkVersionOption: ‘default’​

●​ Click Run Pipeline

Step 10: View Results

You will see stages like:

●​ Build success/failure​

●​ Test summary with pass/fail count​

●​ Code coverage results


Experiment Creating Release Pipelines on Azure, covering
11:
deployment to Azure App Services, managing secrets with Azure Key
Vault, and enabling Continuous Deployment using Azure Pipelines.

Objective:

●​ Deploy applications to Azure App Services​

●​ Manage secrets/configuration using Azure Key Vault​

●​ Perform Continuous Deployment (CD) using Azure Pipelines


Step 1: Enable Classic Pipeline Support

1.​ Go to your Azure DevOps Organization Settings​

2.​ Navigate to Pipelines → Settings​

3.​ Turn OFF the toggle for "Disable creation of classic pipelines"​

Step 2: Create a New Release Pipeline

1.​ Go to Pipelines → Releases​

2.​ Click on "New Pipeline"​

3.​ Choose a template (e.g., Azure App Service Deployment)​

Step 3: Add Artifacts

1.​ Click “Add an artifact”​

2.​ Select the source (e.g., Build Pipeline output)​

3.​ Click Add

Step 4: Create Stages and Configure Tasks

1.​ Click on Stage 1 (e.g., “Deploy”)​

2.​ Add deployment tasks, such as:​

○​ Azure App Service Deploy​


○​ Key Vault secrets fetch task​

3.​ Provide App Service name, subscription, and other settings​

Step 5: Link Azure Key Vault (Optional but Recommended)

1.​ In your pipeline task, add Azure Key Vault task​

2.​ Select your Azure Subscription and Key Vault​

3.​ Choose secrets to download for use in your app​

Step 6: Enable Continuous Deployment Trigger

1.​ Go to the Artifact section​

2.​ Enable "Continuous Deployment Trigger"​

This will trigger the release pipeline when a new build is available

Step 8: Test Plan (Optional)

You can integrate Azure Test Plans to run automated or manual tests as part of the
pipeline.​
Experiment 12: Practical Exercise and Wrap-Up: Build and Deploy a complete DevOps
Pipeline, Discussion on Best Practices and Q&A

In this experiment, you will create an end-to-end DevOps pipeline that demonstrates the
following processes:

• Version Control: Code is maintained in a Git repository (e.g., GitHub or Azure Repos).

• Continuous Integration (CI): A CI tool (Jenkins and/or Azure Pipelines) automatically


checks out the code, builds it using Maven/Gradle, runs unit tests, and archives the build
artifact.

• Artifact Management: The artifact (e.g., a JAR file) is archived and made available for
deployment.

• Continuous Deployment (CD): Deployment automation is handled either by an Ansible


playbook or an Azure Release pipeline, deploying the artifact to a target environment (such
as an Azure App Service or a local server).

• Secrets and Configuration Management: Securely manage configuration details and


secrets using Azure Key Vault.

• Pipeline as Code: Use YAML (for Azure Pipelines) or a Jenkinsfile (for Jenkins) to define
your build and release processes.

Step 1: Code Repository Preparation(Program 6)

Step 2: Continuous Integration with Jenkins and/or Azure Pipelines(Program 4, 7)

Step 3: Artifact Management(Program 8)

Step 4: Deployment Automation with Ansible( Program 8)

Step 5: End-to-End Pipeline Demonstration(Program 6)

Best Practices:

1.​ Pipeline as Code: Use YAML (or a Jenkinsfile) to define your build and
release pipelines. This allows you to version control your pipeline
configuration alongside your code.
2.​ Automate Everything:Automate code checkout, builds, tests, artifact archiving,
and deployments. Reduce manual interventions to minimize human error.
3.​ Idempotence: Ensure that your deployment scripts (whether Ansible
playbooks or release tasks) are idempotent—running them multiple times
produces the same result.
4.​ Monitoring and Logging: Integrate logging and monitoring into your pipeline.
Review test reports, deployment logs, and set up notifications for build
failures.

You might also like