Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 43

Sign up

Search

DevSecOps (DevOps) Project:


Deploying a Petshop Java-Based
Application with CI/CD, Docker, and
Kubernetes
Harshit Gupta · Follow
17 min read · Jun 15, 2024

19

Sign up to discover human stories that deepen your understanding of the world.

Membership

Free
Access the best member-only stories.

Distraction-free reading. No ads. Support independent authors.

Organize your knowledge with lists and


Listen to audio narrations. Read
highlights.
offline.
Tell your story. Find your audience.
Join the Partner Program and earn for your
writing.
Sign up for free

Try for $5/month


Dwight The Legend !!!

Sign up to discover human stories that deepen your understanding of the world.
Introduction
In this blog, I will walk you through the process of deploying a Petshop
Membership
Java- Based Application using Jenkins as a CI/CD tool. This deployment
utilizes
Free Docker for containerization, Kubernetes for container
Access the best member-only stories.
orchestration, and incorporates various security measures and
Distraction-free reading. No ads. Support independent authors.
automation tools like Terraform, SonarQube, Trivy, and Ansible. This
Organize your knowledge with lists and
project showcases a comprehensive approach Listen
highlights. to modern application
to audio narrations. Read

deployment, emphasizing automation, security,


Tell your story. Find your audience.
and scalability.
offline.

Join the Partner Program and earn for your


writing.
Throughout this project, I faced and solved numerous challenges
independently, which significantly enhanced my problem-solving skills and
deepened my understanding of the technologies involved.🔍🛠
Special thanks to Ajay Kumar Yegireddi for providing the project and his
detailed blog, which was instrumental in helping me complete this project
successfully.

This project was an incredible learning experience, providing hands-on


practice with a variety of tools and technologies critical for modern DevOps
practices. I’m excited to share my work and look forward to any feedback or
questions you might have! 💬

Warning⚠
Before proceeding, ensure you read and understand the code properly. Make
necessary changes to variables such as GitHub repository URLs,
credentials, DockerHub usernames etc. Failure to update these variables
can affect the deployment process. Always double-check configurations and
ensure they align with your environment.
Sign up to discover human stories that deepen your understanding of the world.

Membership
Project
Free
Overview
Access the best member-only stories.
The goal of this project is to deploy a Java-based Petshop application in a
Distraction-free reading. No ads. Support independent authors.
secure, scalable, and automated manner. Here are the key components and
Organize your knowledge with lists and
tools used: Listen to audio narrations. Read
highlights.
offline.
Tell your story. Find your audience.
Jenkins for Continuous Integration and Continuous
Join the Partner Deployment
Program and earn for your
(CI/CD) writing.

Docker for containerizing the application

Kubernetes for orchestrating the containers

Terraform for Infrastructure as Code (IaC)

SonarQube for static code analysis and quality assurance


Trivy for container security scanning

Ansible for configuration management

CI/CD Pipeline for Petshop Java-Based Application Deployment


The Continuous Integration/Continuous Deployment (CI/CD) pipeline is
a crucial component in modern software development, enabling teams to
deliver high-quality software efficiently and reliably. Below is an
explanation of the CI/CD pipeline for the Petshop Java-Based Application,
illustrated in the provided image.

Sign up to discover human stories that deepen your understanding of the world.

Membership

Free
Access the best member-only stories.

Distraction-free reading. No ads. Support independent authors.

Organize your knowledge with lists and


Listen to audio narrations. Read
highlights.
offline.
Pipeline Overview
Tell your story. Find your audience.
Join the Partner Program and earn for your
1. Dev Team: The development team writes and commits code to a
writing.
shared repository.

2. GitHub: The code repository where the project is hosted. Developers


commit their code changes to GitHub.
3. Jenkins: The CI/CD tool that automates the build, test, and deployment
processes. Jenkins listens for code commits and triggers the pipeline.

4. Maven: Used for building and compiling the Java application.

5. Dependency-Check: A tool that scans for vulnerable dependencies


during the build process.

6. Ansible: Manages configurations and deployment using playbooks,


integrating with Docker.

7. Docker: Containerizes the application for consistent environments


across development, testing, and production.

8. SonarQube: Performs static code analysis to ensure code quality and


security.

9. Trivy: Scans Docker images for vulnerabilities to maintain secure


deployments.

10. Kubernetes: Orchestrates the deployment of containerized applications,


Sign upmanaging
to discoverscaling
humanand operations.
stories that deepen your understanding of the world.

Detailed Pipeline Explanation


Membership
1. Commit to GitHub:
Free
• Action: Developers write code and commit their
Access changes
the best member-onlyto the GitHub
stories.

repository.
Distraction-free reading. No ads. Support independent authors.

• Importance: Centralized
Organize your knowledge with lists and code management ensures version control and
Listen to audio narrations. Read
highlights.
collaboration.
offline.
Tell your story. Find your audience.
2. Jenkins Build Trigger: Join the Partner Program and earn for your
• Action: Jenkins monitors the GitHub repository
writing. for new commits.

When a new commit is detected, Jenkins triggers the pipeline.


• Importance: Automates the integration process, reducing manual
intervention and speeding up development cycles.
3. Maven Build:
•Action: Jenkins uses Maven to build the project. Maven compiles the
code and packages it into a deployable format (e.g., a JAR file).
•Importance: Ensures that the application can be consistently built
from source code.

4. Dependency-Check:
•Action: Maven integrates with Dependency-Check to scan
for vulnerabilities in the project’s dependencies.
•Importance: Identifies and mitigates potential security risks in third-
party libraries early in the development process.

5. Ansible Docker Playbook:


• Action: Ansible playbooks automate the setup of Docker containers.
Jenkins uses Ansible to ensure that the Docker environment is correctly
configured.
• Importance: Simplifies environment setup and configuration
management, ensuring consistency across different environments.
Sign up to discover
6. Docker human stories that deepen your understanding of the world.
Containerization:
• Action: The application is containerized using Docker, which
packages the application and its dependencies into a container.
Membership
• Importance: Containers provide a consistent runtime environment,
reducing
Free issues related to “works on my machine” syndrome.
Access the best member-only stories.

7. Maven Compile
Distraction-free reading.and
No ads.Test: Support independent authors.
• Action: Maven compiles the code and runs tests to verify that the
Organize your knowledge with lists and
Listen to audio narrations. Read
application
highlights. works as expected.
offline.
• Importance:
Tell your story. FindAutomated
your audience. testing ensures that code changes do not
Join the Partner Program and earn for your
introduce new bugs.
writing.

8. SonarQube Analysis:
• Action: Jenkins integrates with SonarQube to perform static code
analysis, checking for code quality and security issues.
•Importance: Maintains high code quality and security standards,
ensuring that the application is reliable and maintainable.

9. Trivy Security Scan:


•Action: Trivy scans Docker images for known vulnerabilities
before deployment.
•Importance: Ensures that the deployed containers are secure and free
from critical vulnerabilities.

10. Kubernetes Deployment:


•Action: Jenkins deploys the containerized application to a Kubernetes
cluster.
•Importance: Kubernetes manages the deployment, scaling, and
operations of the application, ensuring high availability and reliability.

The Main Question: Why This CI/CD Pipeline is Necessary???


Automation: Automates the entire build, test, and deployment process,
reducing manual effort and increasing efficiency.
Sign up to discover human stories that deepen your understanding of the world.
Consistency: Ensures that the application behaves the same way in
development, testing, and production environments.
Membership
Quality Assurance: Integrates tools like SonarQube and Dependency-
Free
Check to maintain code quality and security.
Access the best member-only stories.

Security: Uses
Distraction-free Trivy
reading. No ads.to scan for vulnerabilities,
Supportensuring that only secure
independent authors.

images
Organize are deployed.
your knowledge with lists and
Listen to audio narrations. Read
highlights.
Scalability: Deploys the application on Kubernetes,
Tell your story. Find your audience.
offline. enabling it to scale
seamlessly based on demand. Join the Partner Program and earn for your
writing.
Reliability: Automated testing and analysis ensure that new code
changes do not break the application, maintaining its reliability.

In conclusion, this CI/CD pipeline is essential for delivering a robust,


secure, and scalable Petshop Java-Based Application. By automating the
entire process, it ensures that the application is always in a deployable
state, with high code quality and security standards maintained
throughout the development lifecycle.

Why Docker and Kubernetes(K8s) both?


Using both Docker and Kubernetes together in a CI/CD pipeline brings a
combination of benefits that leverage the strengths of each technology.
Here’s an explanation of why both are used in the context of deploying a
Petshop Java-Based Application:

Docker: Containerization
1. Consistent Environment: Docker packages applications with all their
dependencies into containers. This ensures that the application runs the
same way regardless of where it is deployed, eliminating the “works on
my machine” problem.

2. Isolation: Containers provide process isolation, which means that each


Sign upapplication
to discover runs
humanin stories
its ownthat
environment without
deepen your interfering
understanding with
of the others.
world.
This isolation improves security and reliability.

3. Lightweight: Docker containers are lightweight and start quickly


Membership
compared to virtual machines, making them ideal for microservices and
modern
Free application architectures.
Access the best member-only stories.

4. Portability:
Distraction-free Containers
reading. No ads. can run on any system that
Support supports
independent authors. Docker,

providing portability across different environments (development,


Organize your knowledge with lists and
Listen to audio narrations. Read
testing,
highlights.production).
offline.
Tell your story. Find your audience.
Kubernetes: Orchestration Join the Partner Program and earn for your
writing.
1. Scalability: Kubernetes automates the scaling of applications based on
demand. It can automatically increase or decrease the number of
running containers to handle varying loads.
2. Load Balancing: Kubernetes provides built-in load balancing to
distribute traffic across multiple containers, ensuring high availability
and performance.

3. Self-Healing: Kubernetes can automatically restart failed containers,


replace containers, and reschedule containers when nodes fail, ensuring
the application remains available.

4. Automated Deployment: Kubernetes manages the deployment of


containers, making rolling updates and rollbacks easier. This ensures
smooth and uninterrupted application updates.

5. Resource Management: Kubernetes efficiently manages resources like


CPU and memory across the cluster, optimizing utilization and
performance.

Combined Benefits
1. Development to Production: Docker is ideal for packaging and running
individual applications during development. Kubernetes takes these
Sign up to discover human stories that deepen your understanding of the world.
Docker containers and provides the infrastructure to run them reliably
at scale in production.

2. Microservices Architecture: Using Docker for individual microservices


Membership
and Kubernetes to manage these microservices allows for a flexible,
Free
Access the best member-only stories.
scalable, and resilient architecture.
Distraction-free reading. No ads. Support independent authors.
3. Complex Applications: For applications with multiple components (like
Organize your knowledge with lists and
the Petshop Java-Based Application), Kubernetes
highlights.
Listen to audiocan orchestrate
narrations. Read the
deployment of each component, manage offline.
Tell your story. Find your audience.
their interdependencies,
and ensure they work together seamlessly.
Join the Partner Program and earn for your
writing.
4. CI/CD Integration: In a CI/CD pipeline, Docker ensures that the same
containerized application is tested and deployed across different stages.
Kubernetes ensures that the deployment to production is managed,
scalable, and resilient.
Example Workflow

Containerization with Docker:


•Developers write code and build a Docker image for the application.
•This Docker image includes the application and all its dependencies, ensuring
it runs consistently across different environments.

Orchestration with Kubernetes:


•The Docker image is pushed to a container registry.
•Kubernetes pulls the Docker image from the registry and deploys it to a cluster.
•Kubernetes manages the scaling, load balancing, and self-healing of
the application.

:::Detailed Step-by-Step Guide:::

Step 1: Create an Ubuntu (22.04) T2 Large Instance using Terraform


I am using Terraform IaC to launch an EC2 instance on AWS rather than
Sign up to discover human stories that deepen your understanding of the world.
doing traditionally, so I assume you know how to set up AWS CLI and use
a Terraform. Create a main.tf file with the following Terraform
configuration to provision an AWS EC2 instance:
Membership

Free
Access the best member-only stories.

# Distraction-free
Provider configuration
reading. No ads. Support independent authors.
provider "aws" {
Organize
region your knowledge with lists# and
= "ap-south-1" Specify the region Listen to audio narrations. Read
} highlights.
offline.
Tell your story. Find your audience.
# Create a new security group that allows all inbound and outbound traffic
resource "aws_security_group" "allow_all" { Join the Partner Program and earn for your
name = "allow_all_traffic" writing.
description = "Security group that allows all inbound and outbound traffic"

ingress {
from_port =
0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}

egress {
from_port =
0
to_port = 0
protocol = "-1"
cidr_blocks =
["0.0.0.0/0"]
}
}

# Launch an EC2 instance


resource "aws_instance" "my_ec2_instance"
{ ami = "ami-0f58b397bc5c1f2e8"
instance_type = "t2.large"
key_name = "MyNewKeyPair"
security_groups = [aws_security_group.allow_all.name]

# Configure root block


device root_block_device {
volume_size = 30
}

tags = {
Name = "MyUbuntuInstance"
}
}

Sign up to discover human stories that deepen your understanding of the world.

Initialize and apply the Terraform configuration:


Membership

Free
Access the best member-only stories.
terraform
Distraction-free
init terraform reading. No ads. Support independent authors.
apply
Organize your knowledge with lists and
Listen to audio narrations. Read
highlights.
offline.
Tell your story. Find your audience.
Join the Partner Program and earn for your
Step 2: Install Jenkins, Docker, and Trivy writing.

SSH into the EC2 instance with your key pair and run the
following commands:
# Install Jenkins
wget -q -O - https://pkg.jenkins.io/debian/jenkins.io.key | sudo apt-key add -
sudo sh -c 'echo deb http://pkg.jenkins.io/debian-stable binary/ >
/etc/apt/sources. sudo apt update -y
sudo apt install jenkins -
y sudo systemctl start
jenkins sudo systemctl
enable jenkins

# Install Docker
sudo apt install apt-transport-https ca-certificates curl software-properties-
common curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add
-
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $
sudo apt update -y
sudo apt install docker-ce -
y sudo usermod -aG docker $
{USER} newgrp docker
sudo chmod 777 /var/run/docker.sock

# Install Trivy
sudo apt install wget apt-transport-https gnupg lsb-release -y
wget -qO - https://aquasecurity.github.io/trivy-repo/deb/public.key | sudo apt-key a
echo deb https://aquasecurity.github.io/trivy-repo/deb $(lsb_release -sc) main |
sud sudo apt update -y
sudo apt install trivy -y

Sign up to discover human stories that deepen your understanding of the world.
since Apache Maven’s default proxy is 8080, we need to change the port of
Jenkins from 8080 to let’s say 8090, for that:

Membership

Free
Access the best member-only stories.
sudo systemctl stop jenkins
sudo systemctl
Distraction-free status
reading. jenkins
No ads. Support independent authors.
cd /etc/default
sudo vi your
Organize jenkins
knowledge#chnage port HTTP_PORT=8090 and save and
with lists and
Listen to audio narrations. Read
exit cd /lib/systemd/system
highlights.
sudo vi jenkins.service #change Environments="Jenkins_port=8090"
offline. save and exit
Tell your
sudo story. Finddaemon-reload
systemctl your audience.
sudo systemctl restart jenkins Join the Partner Program and earn for your
sudo systemctl status jenkins writing.

Now, grab your Public IP Address


<EC2 Public IP Address:8090> # for jenkins password
sudo cat /var/lib/jenkins/secrets/initialAdminPassword
# change the password once you set up jenkins server

Sign up to discover human stories that deepen your understanding of the world.

After the docker installation, we create a SonarQube container:


Membership

Free
Access the best member-only stories.
docker run -d --name sonar -p 9000:9000 sonarqube:lts-community
Distraction-free reading. No ads. Support independent authors.

Organize your knowledge with lists and


Listen to audio narrations. Read
highlights.
Now our SonarQube is up and running. offline.
Tell your story. Find your audience.
Enter username and password, click on login and
Join thechange password
Partner Program and earn for your
writing.

username
admin password
admin
Step 3: Install Plugins in Jenkins
In Jenkins, navigate to Manage Jenkins -> Available Plugins and install the
following plugins:

Sign upJDK (Eclipse Temurin Installer)


to discover human stories that deepen your understanding of the world.
SonarQube Scanner

Maven
Membership
OWASP
Free Dependency Check
Access the best member-only stories.

Distraction-free reading. No ads. Support independent authors.


Configure Java and Maven in Global Tool Configuration
Go toOrganize
Manage Jenkins
your knowledge listsTools
with→ and → Install JDK(17) and
Listen Maven3(3.6.0)
to audio narrations. Read → Click
highlights.
on Apply and Save offline.
Tell your story. Find your audience.
Join the Partner Program and earn for your
writing.
Sign up to discover human stories that deepen your understanding of the world.

Membership

Free
Access the best member-only stories.

Distraction-free reading. No ads. Support independent authors.

Organize your knowledge with lists and


Listen to audio narrations. Read
highlights.
offline.
Tell your story. Find your audience.
Join the Partner Program and earn for your
writing.
Sign up to discover human stories that deepen your understanding of the world.

Create a New Job with a Pipeline option: Membership

Free
Access the best member-only stories.

Distraction-free reading. No ads. Support independent authors.

Organize your knowledge with lists and


Listen to audio narrations. Read
highlights.
offline.
Tell your story. Find your audience.
Join the Partner Program and earn for your
writing.

Pipeline script:
pipeline{
agent
any
tools {
jdk 'jdk17'
maven
'maven3'
}
stages{
stage ('clean Workspace'){
steps{
cleanWs()
}
}
stage ('checkout scm') {
steps {
git 'https://github.com/<your-java-project-repo-or-fork-one>' #https
}
}
stage ('maven compile') {
steps {
sh 'mvn clean compile'
}
}
stage ('maven Test') {
steps {
sh 'mvn test'
}

Sign up to discover human stories that deepen your understanding of the world.
}
}

Membership

Free
Access the best member-only stories.

Distraction-free reading. No ads. Support independent authors.

Organize your knowledge with lists and


Listen to audio narrations. Read
highlights.
offline.
Tell your story. Find your audience.
Join the Partner Program and earn for your
writing.
Step 4: Configure SonarQube Server in Jenkins
Retrieve the Public IP Address of your EC2 instance. Since SonarQube
operates on Port 9000, you can access it via <Public IP>:9000 .
To proceed, navigate to your SonarQube server, then follow these steps:
Click on Administration → Security → Users → Tokens. Next, update and
copy the token by providing a name and clicking on Generate Token.

Go to the Jenkins Dashboard, then navigate to Manage Jenkins →


Credentials
→ Add Secret Text. The screen should look like this:
Sign up to discover human stories that deepen your understanding of the world.

Membership

Free
Access the best member-only stories.

Distraction-free reading. No ads. Support independent authors.

Organize your knowledge with lists and


Listen to audio narrations. Read
highlights.
offline.
Tell your story. Find your audience.
Join the Partner Program and earn for your
writing.

Next, go to the Jenkins Dashboard, then navigate to Manage Jenkins →


System, and add the necessary configuration as shown in the image below.
Click on apply and save

Now, we will install a sonar scanner in the tools.

Sign up to discover human stories that deepen your understanding of the world.

Membership

Free
Access the best member-only stories.

Distraction-free reading. No ads. Support independent authors.

Organize your knowledge with lists and


Listen to audio narrations. Read
highlights.
offline.
Tell your story. Find your audience.
Join the Partner Program and earn for your
writing.
Click on apply and save

In the SonarQube Dashboard, add a quality gate by navigating to


Administration → Configuration → Webhooks.

Add details

#Name- jenkins
#in url section of quality gate
<http://jenkins-public-ip:8090>/sonarqube-webhook/
#leave the secret box blank
Sign up to discover human stories that deepen your understanding of the world.

Now add this script in pipeline (Dashboard→ petstore→


Membership
configuration) and
test the steps of SonarQube which we did:
Free
Access the best member-only stories.

Distraction-free reading. No ads. Support independent authors.

Organizetools
#under your knowledge
section withadd
lists and
this environment Listen to audio narrations. Read
highlights.
environment {
SCANNER_HOME=tool 'sonar-scanner' offline.
Tell your story. Find your audience.
}
# in stages add this Join the Partner Program and earn for your
stage("Sonarqube Analysis "){ writing.
steps{
withSonarQubeEnv('sonar-server') {
sh ''' $SCANNER_HOME/bin/sonar-scanner -Dsonar.projectName=Petsh
-Dsonar.java.binaries=. \
-Dsonar.projectKey=Petshop '''
}
}
}
stage("quality gate"){ steps {
script {
waitForQualityGate abortPipeline: false, credentialsId: 'Sonar-tok
}
}
}

Apply, save and build. Now, go to your SonarQube Server and go to project:

you can see the result

Step 5: Install OWASP Dependency Check Plugins


Sign up to discover human stories that deepen your understanding of the world.
Go to the Jenkins Dashboard, then click on Manage Jenkins → Plugins. Find
the OWASP Dependency-Check plugin, click on it, and install it without
requiring a restart.
Membership

Free
After installing the plugin, proceed to configure thethetool
Access by navigating
best member-only stories. to
Dashboard → Manage
Distraction-free Jenkins → Tools →.
reading. No ads. Support independent authors.

Organize your knowledge with lists and


Listen to audio narrations. Read
highlights.
offline.
Tell your story. Find your audience.
Join the Partner Program and earn for your
writing.
apply and save

SignAdd
up tothe script of OWASP in pipeline now:
discover human stories that deepen your understanding of the world.

stage ('Build war file'){ Membership


steps{
Free sh 'mvn clean install -DskipTests=true'
} Access the best member-only stories.
}
Distraction-free reading. No ads. Support independent authors.
stage("OWASP Dependency Check")
{ steps{
Organize your knowledge with lists and
Listen to audio narrations. Read
highlights. dependencyCheck additionalArguments: '--scan ./ --format XML ',
odcI dependencyCheckPublisher pattern: '**/dependency-check-
offline.
Tell your story. Findreport.xml'
your audience.
} Join the Partner Program and earn for your
} writing.

Apply, save and build.


You can see the report,

Sign up to discover human stories that deepen your understanding of the world.

Membership

Free
Access the best member-only stories.

Distraction-free reading. No ads. Support independent authors.

Organize your knowledge with lists and


Listen to audio narrations. Read
highlights.
offline.
Tell your story. Find your audience.
Join the Partner Program and earn for your
writing.

tired???
Step 6: Docker Set-up
In Jenkins, navigate to Manage Jenkins -> Available Plugins and install
these:
- Docker

- Docker Commons

- Docker Pipeline

- Docker API

- docker-build-step

Now, go to Dashboard → Manage Jenkins → Tools →

Sign up to discover human stories that deepen your understanding of the world.

apply and save


Membership

Free
Add DockerHub Username and Password (Access Token) in stories.
Access the best member-only
Global Credentials:
Distraction-free reading. No ads. Support independent authors.

Organize your knowledge with lists and


Listen to audio narrations. Read
highlights.
offline.
Tell your story. Find your audience.
Join the Partner Program and earn for your
writing.
Step 7: Adding Ansible Repository and Install Ansible
Connect to your instance via SSH and run this commands, to install Ansible
on your server:

Sign up to discover human stories that deepen your understanding of the world.
sudo apt update -y
sudo apt install software-properties-common -y
sudo add-apt-repository --yes --update ppa:ansible/ansible
sudo apt install ansible -y
sudo apt install ansible-core -y Membership
ansible --version #to check if it installed properly or not
Free
Access the best member-only stories.

Distraction-free reading. No ads. Support independent authors.

To add inventory
Organize you
your knowledge withcan create a new directory
lists and or add in the default
Listen to audio narrations. Read
highlights.
Ansible hosts file
offline.
Tell your story. Find your audience.
Join the Partner Program and earn for your
writing.

cd
/etc/ansible
sudo vi hosts

[local]
<Ip-of-Jenkins>

save and exit.

Install Ansible Plugins by navigating to Manage Jenkins -> Available


Plugins.

Now add Credentials to invoke Ansible with Jenkins.

Sign up to discover human stories that deepen your understanding of the world.

Membership
In the
FreePrivate key section, paste your .pem key file content directly.
Access the best member-only stories.

CheckDistraction-free
your Ansible reading. No ads.
path on the server by, Support independent authors.

Organize your knowledge with lists and


Listen to audio narrations. Read
highlights.
offline.
Tell your story. Find your audience.
which ansible Join the Partner Program and earn for your
writing.

copy the path and paste it here:


Now, create an Ansible playbook that builds a Docker image, tags it, pushes
it to Docker Hub, and then deploys it in a container using Ansible.

It is already in github repo but you need to modify with your


DockerHub
credentials:
Sign up to discover human stories that deepen your understanding of the world.

Membership

Free
Access the best member-only stories.

Distraction-free reading. No ads. Support independent authors.

Organize your knowledge with lists and


Listen to audio narrations. Read
highlights.
offline.
Tell your story. Find your audience.
Join the Partner Program and earn for your
writing.
Include this stage in the pipeline to build the Docker image, push it to
Docker Hub, and run the container:

stage('Install Docker') {
steps {
dir('Ansible'){ script {
ansiblePlaybook credentialsId: 'ssh', disableHostKeyCheckin
}
}
}
}

Now after build process of the pipeline you would be able to see the result
of web application by visiting the below url:

<jenkins-ip:8081>/jpetstore
Sign up to discover human stories that deepen your understanding of the world.

Membership

Free
Access the best member-only stories.

Distraction-free reading. No ads. Support independent authors.

Organize your knowledge with lists and


Listen to audio narrations. Read
highlights.
offline.
Tell your story. Find your audience.
Join the Partner Program and earn for your
writing.

Step 8: Kubernetes Setup


Create two instance for Kubernetes Master-Slave set up, you can use the
below terraform code or create traditionally by using AWS Console:
# Provider configuration
provider "aws" {
region = "ap-south-1" # Specify the region
}

# Create a new security group that allows all inbound and outbound traffic
resource "aws_security_group" "allow_all" {
name = "allow_all_traffic"
description = "Security group that allows all inbound and outbound traffic"

ingress {
from_port =
0
to_port = 0
protocol = "-1"
cidr_blocks =
["0.0.0.0/0"]
}

egress {
from_port =
0
to_port = 0
protocol = "-1"
cidr_blocks =
["0.0.0.0/0"]
}
}

Sign up #resource
toLaunch
discover human stories that deepen your understanding of the world.
the first EC2 instance
"aws_instance" "my_ec2_instance1" {
ami = "ami-0f58b397bc5c1f2e8" # Ensure this AMI ID is valid for
your r instance_type = "t2.medium"
key_name = "MyNewKeyPair"
security_groups = [aws_security_group.allow_all.name]
Membership

Free
# Root block device with default size (8 GB for most Linux AMIs)
root_block_device { Access the best member-only stories.
volume_size = 8
Distraction-free reading. No ads. Support independent authors.
}
Organize your knowledge with lists and
tags = { Listen to audio narrations. Read
highlights.
Name = "k8s-master"
offline.
Tell
} your story. Find your audience.
} Join the Partner Program and earn for your
writing.
# Launch the second EC2 instance
resource "aws_instance" "my_ec2_instance2" {
ami = "ami-0f58b397bc5c1f2e8" # Ensure this AMI ID is valid for
your r instance_type = "t2.medium"
key_name = "MyNewKeyPair"
security_groups = [aws_security_group.allow_all.name]
}

tags = {
Name = "k8s-slave"
}

Install Kubectl and Minikube on Jenkins machine,

# Install kubectl
sudo apt-get update
sudo apt-get install -y apt-transport-https gnupg2 curl
curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add
- echo "deb https://apt.kubernetes.io/ kubernetes-xenial main" | sudo tee
/etc/apt/sou sudo apt-get update
sudo apt-get install -y kubectl
kubectl version --client

# Install Minikube
curl -LO https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd6
sudo install minikube-linux-amd64 /usr/local/bin/minikube
minikube start
Sign up to discover human stories that deepen your understanding of the world.

for simplicity, connect both newly created instance via SSH in side-by-side
Membership
terminal and change their hostname to master and worker, we can do by
Free
using this command: Access the best member-only stories.

Distraction-free reading. No ads. Support independent authors.

Organize your knowledge with lists and


Listen to audio narrations. Read
highlights.
sudo su
offline.
Tell your story.
hostname masterFind #and
your audience.
worker in second one
bash Join the Partner Program and earn for your
clear writing.

Now run this commands in both master and worker node:


sudo apt-get update

sudo apt-get install -y docker.io


sudo usermod –aG docker Ubuntu
newgrp docker
sudo chmod 777 /var/run/docker.sock

sudo curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key


ad sudo tee /etc/apt/sources.list.d/kubernetes.list <<EOF
deb https://apt.kubernetes.io/ kubernetes-xenial
main EOF

sudo apt-get update

echo "deb [signed-by=/etc/apt/keyrings/kubernetes-apt-keyring.gpg] https://pkgs.k8s.


curl -fsSL https://pkgs.k8s.io/core:/stable:/v1.28/deb/Release.key | sudo gpg --
dear sudo apt update
sudo apt install -y kubelet kubeadm

kubectl sudo snap install kube-apiserver

Sign up to discover human stories that deepen your understanding of the world.

Membership

Free
Access the best member-only stories.

Distraction-free reading. No ads. Support independent authors.

Organize your knowledge with lists and


Listen to audio narrations. Read
highlights.
In master instance, offline.
Tell your story. Find your audience.
Join the Partner Program and earn for your
writing.

sudo kubeadm init --pod-network-cidr=10.244.0.0/16


# in case your in root exit from it and run below
commands mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config
kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentati

In worker instance,

sudo kubeadm join <master-node-ip>:<master-node-port> --token <token> --discovery-to

Copy the config file to Jenkins master or the local file manager and save it,
you can find it in master node by,

cd /.kube
cat
config

Sign up to discover human stories that deepen your understanding of the world.
copy it and save it in documents or another folder save it as secret-file.txt.

Install k8s plugins in jenkin, Membership

Free
Access the best member-only stories.

Distraction-free reading. No ads. Support independent authors.

Organize your knowledge with lists and


Listen to audio narrations. Read
highlights.
offline.
Tell your story. Find your audience.
Join the Partner Program and earn for your
writing.
Now, go to Manage Jenkins –> Credentials –>System–> Global Credential–
> Add Credentials

Step 9: Master-Slave Setup for Ansible and Kubernetes


To enable communication with the Kubernetes clients, we need to create an
SignSSH
up tokey on the human
discover Ansiblestories
node that
and deepen
share ityour
withunderstanding
the Kubernetes
ofmaster
the world.
system.

On main (on which we are running jenkin, notMembership


the master-worker) instance,

Free
Access the best member-only stories.

Distraction-free reading. No ads. Support independent authors.


ssh-keygen
Organize your knowledge with lists and
Listen to audio narrations. Read
highlights.
offline.
Tell your story. Find your audience.
Join the Partner Program and earn for your
writing.
Change the directory to .ssh and copy the public key (id_rsa.pub)

Sign up to discover human stories that deepen your understanding of the world.
cd .ssh
cat id_rsa.pub #copy this public key

Membership

Freecopying the public key from the Ansible Main, navigate to the
After .ssh
Access the best member-only stories.
directory on the Kubernetes master machine and
Distraction-free reading. No ads.
paste the copied public
Support independent authors.
key into the authorized_keys file.
Organize your knowledge with lists and
Listen to audio narrations. Read
highlights.
offline.
Tell your story. Find your audience.
Join the Partner Program and earn for your
cd .ssh #on k8s master
writing.
sudo vi authorized_keys

Note: Add the copied public key as a new line in the authorized_keys file
without deleting any existing keys, then save and exit.
By adding the public key from the main to the Kubernetes machine, keyless
access is now configured. To verify, try accessing the Kubernetes master
using the following command format.

ssh ubuntu@<public-ip-k8s-master>

Now, open the hosts file on the Ansible server and add the public IP of the
Kubernetes master.

SignPlease
up to discover
note that human stories that deepen
here Ansible-master your
referring to understanding of the we
Main instance which world.
created first in this project and the other ones are k8s-master and k8s-slave.

Membership

Free
[k8s]
Access the best member-only stories.
public ip of k8s-master
Distraction-free reading. No ads. Support independent authors.

Organize your knowledge with lists and


Listen to audio narrations. Read
highlights.
Test Ansible Master Slave Connection
offline.
Tell your story. Find your audience.
Join the Partner Program and earn for your
writing.

ansible -m ping all #on main instance

Add the stage in pipeline and build the job:


stage('k8s using ansible'){
steps{
dir('Ansible') { script{
ansiblePlaybook credentialsId: 'ssh', disableHostKeyChecking
}
}
}
}

In the Kubernetes cluster give this command

kubectl get all


kubectl get svc

<slave-ip:serviceport(30699)>/jpetstore
# port may vary, you can check it from the above cmd (kubectl get
Sign up to discover human stories that deepen your understanding of the world.
all)

Membership

Free
Access the best member-only stories.

Distraction-free reading. No ads. Support independent authors.

Organize your knowledge with lists and


Listen to audio narrations. Read
highlights.
offline.
Tell your story. Find your audience.
Join the Partner Program and earn for your
writing.

Complete Pipeline:

pipeline{
agent any
tools {
jdk 'jdk17'
maven
'maven3'
}
environment {
SCANNER_HOME=tool 'sonar-scanner'
}
stages{
stage ('clean Workspace'){
steps{
cleanWs()
}
}
stage ('checkout scm') {
steps {
git 'https://github.com/your-github-repo'
}
}
stage ('maven compile') {
steps {
sh 'mvn clean compile'
}
stage ('maven Test')
{ steps {
sh 'mvn test'
}
}
stage("Sonarqube Analysis "){
Sign up to discover human stories that deepen your understanding of the world.
steps{
withSonarQubeEnv('sonar-server') {
sh ''' $SCANNER_HOME/bin/sonar-scanner -Dsonar.projectName=Petst
-Dsonar.java.binaries=. \
-Dsonar.projectKey=Petstore '''
} Membership
}
Free
} Access the best member-only stories.
stage("quality gate")
Distraction-free{reading.
stepsNo{ads. Support independent authors.
script {
Organize your knowledgewaitForQualityGate
with lists and abortPipeline: false,
Listen to audiocredentialsId:
narrations. Read 'Sonar-tok
highlights. }
} offline.
Tell your story. Find your audience.
}
stage ('Build war file'){ Join the Partner Program and earn for your
steps{ writing.
sh 'mvn clean install -DskipTests=true'
}
}
stage("OWASP Dependency Check")
{ steps{
dependencyCheck additionalArguments: '--scan ./ --format XML ',
odcI dependencyCheckPublisher pattern: '**/dependency-check-
report.xml'
}
stage('Ansible docker Docker') {
steps {
dir('Ansible')
{ script {
ansiblePlaybook credentialsId: 'ssh', disableHostKeyChecking
}
}
}
}
stage('k8s using ansible'){
steps{
dir('Ansible') {
script{
ansiblePlaybook credentialsId: 'ssh', disableHostKeyChecking
}
}
}
}
}
}

Conclusion
By following these steps, we successfully deployed a Java-based Petshop
Sign up to discover human stories that deepen your understanding of the world.
application using Jenkins, Docker, Kubernetes, Terraform, SonarQube,
Trivy, and Ansible. This project not only demonstrates a comprehensive
approach to modern application deployment but also highlights the
Membership
importance of automation and security in the DevOps pipeline.
Free
Access the best member-only stories.

This journey has


Distraction-free been
reading. a valuable learning experience,
No ads. fromauthors.
Support independent infrastructure
provisioning
Organize yourto continuous
knowledge with lists andintegration and deployment, containerization,
Listen to audio narrations. Read
highlights.
orchestration, and ensuring robust security measures. I hope this detailed
offline.
guideTell
helps youFind
your story. inyour
your own deployment projects and inspires you to
audience.
Join the Partner Program and earn for your
explore the powerful tools and techniques in the DevSecOps realm.
writing.
Connect to me, if you have any query, want to share or suggest me anything,
here’s my Portfolio or dm me on LinkedIn.
Stay tuned and follow me for more chapters of my odyssey, my projects,
cybersec stories, and write-ups and also thank you for being part of my
story! 🚀

Sign up to discover human stories that deepen your understanding of the world.
Let’s continue to strengthen our skills and build secure, scalable
applications together!
#DevOps #DevSecOps #CI #CD #AWS #Terraform #Jenkins #Docker
Membership
#Kubernetes
Free #SecurityAutomation #SonarQube #Trivy #Ansible
Access the best member-only stories.

Distraction-free reading. No ads. Support independent authors.

Organize your knowledge with lists and


Listen to audio narrations. Read
DevOps
highlights. Devsecops Docker Kubernetes Jenkins
offline.
Tell your story. Find your audience.
Join the Partner Program and earn for your
19
writing.
Follow
Written by Harshit Gupta
33 Followers

Just a cybersec guy !!!

More from Harshit Gupta

Sign up to discover human stories that deepen your understanding of the world.
Harshit Gupta Harshit Gupta

Deploy a Docker Container with An Introduction to DevSecOps:


AWS ECS and Terraform Enhancing AWS Cloud Security
Membership
Hello everyone, Hello, and welcome back to my blog! After a brief
Free
hiatus forAccess
college
theexams, I’m excitedstories.
best member-only to…

Feb 19 Distraction-free
10 reading. No ads. May 22 Support
16 independent authors.

Organize your knowledge with lists and


Listen to audio narrations. Read
highlights.
offline.
Tell your story. Find your audience.
Join the Partner Program and earn for your
writing.

Harshit Gupta Harshit Gupta


Host Your Website on AWS for Free: Securing the Skies: A Journey in
S3 Bucket and CloudFront AWS Cloud Security and Beyond Hey
Hello, tech enthusiasts!!! I want to share a part of my there!!👋
experience to hosting website on AWS…

Jan 23 4 Mar 6 8 1

Recommended from Medium

Sign up to discover human stories that deepen your understanding of the world.

Membership

Free
Access the best member-only stories.
Yasin Emir Akbaş Szilárd Mátis in The Quantified World
Distraction-free reading. No ads. Support independent authors.
Terraform Modules and import
Organize your knowledge with lists and
Setup Grafana and Prometheus
Listen to Compose
with Docker audio narrations. Read
The purpose of this hands-on training is to
highlights.
provide you with knowledge of Terraform… How to run Grafana and Prometheus in
offline.
Tell your story. Find your audience.
Docker
Join the Partner Program and earn for your
writing.
Jun 13 9 Mar 15 157 3

Lists
Coding & Development General Coding Knowledge
11 stories · 675 saves 20 stories · 1332 saves

Natural Language Processing Productivity


1546 stories · 1083 saves
241 stories · 481 saves

Treesakul Tongsaree (Prym) Rob Golder in Lydtech Consulting

Sealed Secrets: Prevent Exposure Monitoring & Alerting: Prometheus, of


Kubernetes Secret Manifests o… Grafana & Alertmanager—Part 2:…
Imagine you’re managing a Kubernetes In this second part of the series on monitoring
cluster and need to store sensitive informati… and alerting with Prometheus, Grafana and…

Sign up Jun
to13discover
4 human stories that deepen your
May 5understanding
74 1 of the world.

Membership

Free
Access the best member-only stories.

Distraction-free reading. No ads. Support independent authors.

Organize your knowledge with lists and


Listen to audio narrations. Read
highlights.
offline.
Tell your story. Find your audience.
Join the Partner Program and earn for your
writing.
Golaneduard ByteCook

Configure CI/CD pipeline: GitlabCI, 10 Troubleshooting Commands for Linux


ArgoCD, HelmCharts & SOPS Systems
We are in a period where we already have a diverse 1. How to view processes consuming the most CPU?
range of solutions and options for…

May 6 16
May 11 414 1

See more recommendations

Sign up to discover human stories that deepen your understanding of the world.

Membership

Free
Access the best member-only stories.

Distraction-free reading. No ads. Support independent authors.

Organize your knowledge with lists and


Listen to audio narrations. Read
highlights.
offline.
Tell your story. Find your audience.
Join the Partner Program and earn for your
writing.

You might also like