What is CI/CD:
Continuous Integration (CI) and Continuous Delivery/Continuous Deployment (CD) are integral concepts in modern software development practices, and Jenkins is a popular tool for implementing these processes.
Continuous Integration (CI):
CI involves regularly integrating code changes from multiple contributors into a shared repository. The primary goal is to detect and address integration issues early in the development process.
In Jenkins, CI is often achieved through automated builds triggered by events such as code commits to version control systems (e.g., Git). Jenkins can be configured to automatically pull the latest code, build the application, and run tests.
The CI pipeline ensures that the codebase is always in a consistent and functional state, reducing the likelihood of integration problems that can arise when different developers work on different parts of the code.
Continuous Delivery (CD):
Continuous Delivery extends the principles of CI by automating the process of delivering the application to staging or pre-production environments. The goal is to have a reliable and automated deployment process, making it easier to release changes to users at any time.
Jenkins facilitates Continuous Delivery by defining deployment pipelines that include steps like packaging the application, deploying it to a staging environment, and running additional tests. This process ensures that the application is ready for production deployment but leaves the decision to deploy in the hands of the development or operations team.
Continuous Deployment (CD):
Continuous Deployment takes automation a step further by automatically deploying code changes to production environments once they pass all tests in the CD pipeline.
Jenkins can be configured to implement Continuous Deployment by automating the deployment process to production, reducing manual intervention. However, organizations adopting Continuous Deployment often have strict controls, including thorough testing and monitoring, to ensure the quality and reliability of production releases.
What Is a Build Job?
A "build job" typically refers to a specific task or process in the context of software development and continuous integration/continuous deployment (CI/CD) pipelines. In software development, a "build" is the process of compiling source code, linking libraries, and creating executable files or artifacts that can be run on a computer.
A build job is a set of instructions and commands that automate the process of building a software project. This job is often part of a larger CI/CD pipeline, where various tasks are automated to ensure the efficient and reliable delivery of software. The purpose of a build job is to produce a deployable artifact, such as an executable, library, or package, from the source code.
Build jobs are crucial for maintaining code quality, ensuring consistency across environments, and catching errors early in the development process. They are commonly used in conjunction with version control systems, where developers contribute code changes, and the CI/CD pipeline triggers build jobs to validate and integrate those changes into the project.
Different build systems and tools exist, such as Jenkins, Travis CI, GitLab CI/CD, and others, each providing a framework for defining and executing build jobs. These tools help automate tasks like compilation, testing, and packaging, streamlining the development and deployment processes.
What is Webhook?
A webhook is a mechanism for one system to send real-time data to another system as soon as an event occurs. It is commonly used in web development and integration scenarios to enable communication between different applications or services. Instead of requiring constant polling for updates, a webhook allows systems to push information to each other in a more efficient and event-driven manner.
Here's how a webhook typically works:
Event Occurs:
A specific event, such as a user's action on a website or a change in data, triggers the need for information to be sent to another system.
Webhook Setup:
The system generating the event (source) provides a URL endpoint to the system that needs to receive the information (destination). This URL is the webhook endpoint.
Registration:
The destination system registers or subscribes to the webhook by providing its endpoint URL to the source system.
Event Payload:
When the specified event occurs, the source system immediately sends a payload of data to the registered endpoint (webhook) of the destination system.
Processing:
The destination system processes the received data and takes appropriate actions based on the information provided in the payload.
Webhooks are commonly used in various scenarios, including:
Integration between Services: Webhooks enable seamless communication between different web services and APIs.
Real-time Updates: They are used for receiving real-time updates, such as notifications, changes in data, or user interactions.
Automation: Webhooks are integral to many automation processes, ensuring that systems can react promptly to events.
Popular web services, like GitHub, Stripe, and Slack, offer webhook functionalities. For example, in GitHub, you can set up webhooks to receive notifications about repository events, such as code pushes or pull requests. This allows for automated workflows and integrations with other services.
What is Freestyle Projects ??
A freestyle project in Jenkins is a type of project that allows you to build, test, and deploy software using a variety of different options and configurations. Here are a few tasks that you could complete when working with a freestyle project in Jenkins:
Create Free Style Project (Node-Todo-App):
How to install Jenkins , Docker in AWS EC2 Ubuntu Machine:
Login to AWS Console:
Go to the AWS Management Console (https://aws.amazon.com/).
Sign in with your AWS account.
Navigate to EC2:
In the AWS Management Console, navigate to the EC2 service.
Launch an Instance:
Click on the "Instances" in the left navigation pane.
Click the "Launch Instances" button.
Choose an Amazon Machine Image (AMI):
In the "Step 1: Choose an Amazon Machine Image (AMI)" section, select an Ubuntu AMI. You can search for "Ubuntu" in the search bar and choose an appropriate version (e.g., Ubuntu Server 20.04 LTS).
Choose an Instance Type:
In the "Step 2: Choose an Instance Type" section, select "t2.xlarge" as the instance type.
Click "Next: Configure Instance Details."
Configure Instance Details:
In the "Step 3: Configure Instance Details" section:
Set the "Number of instances" to 1.
Optionally, you can configure additional settings, such as network, subnet, IAM role, etc.
Click "Next: Add Storage."
Add Storage:
In the "Step 4: Add Storage" section, you can leave the default storage settings or adjust as needed.
Click "Next: Add Tags."
Add Tags:
In the "Step 5: Add Tags" section, click "Add Tag."
For "Key," enter "Name" and for "Value," enter "Jenkins" (or your preferred name).
Click "Next: Configure Security Group."
Configure Security Group:
In the "Step 6: Configure Security Group" section:
Create a new security group or use an existing one.
Add inbound rules to allow HTTP (port 80), HTTPS (port 443), and SSH (port 22) traffic.
Click "Review and Launch."
Review and Launch:
Review your configuration settings.
Click "Launch."
Select Key Pair:
In the key pair dialog, select "Choose an existing key pair" and choose the "jenkinsandubuntu" key pair.
Acknowledge that you have access to the private key.
Click "Launch Instances."
View Instances:
Once the instance is launched, you can view it in the EC2 dashboard.
Wait for the instance to reach the "running" state.
Setup docker and Jenkins in ububtu:
Go to Ubuntu Machine and update the ubuntu machine:
sudo apt-get update
After that install docker and docker-compose.
sudo apt-get install docker.io docker-compose -y
After that install to the jenkins
sudo apt update
sudo apt install fontconfig openjdk-17-jre
sudo wget -O /usr/share/keyrings/jenkins-keyring.asc \
https://pkg.jenkins.io/debian-stable/jenkins.io-2023.key
echo deb [signed-by=/usr/share/keyrings/jenkins-keyring.asc] \
https://pkg.jenkins.io/debian-stable binary/ | sudo tee \
/etc/apt/sources.list.d/jenkins.list > /dev/null
sudo apt-get update
sudo apt-get install jenkins
After that In docker group add ubuntu and Jenkins and Reboot the Ubuntu.
sudo usermod -aG docker $USER
sudo usermod -aG docker jenkins
sudo reboot
After that Enable the docker and Jenkins.
sudo systemctl enable jenkins
sudo systemctl enable docker
How to Setup Jenkins in Ubuntu Machine Live:
Showing GitHub File:
1. Docker File:
FROM node:12.2.0-alpine
WORKDIR app
COPY . .
RUN npm install
RUN npm run test
EXPOSE 8000
CMD ["node","app.js"]
2. app.js File
const express = require('express'),
bodyParser = require('body-parser'),
// In order to use PUT HTTP verb to edit item
methodOverride = require('method-override'),
// Mitigate XSS using sanitizer
sanitizer = require('sanitizer'),
app = express(),
port = 8000
app.use(bodyParser.urlencoded({
extended: false
}));
// https: //github.com/expressjs/method-override#custom-logic
app.use(methodOverride(function (req, res) {
if (req.body && typeof req.body === 'object' && '_method' in req.body) {
// look in urlencoded POST bodies and delete it
let method = req.body._method;
delete req.body._method;
return method
}
}));
let todolist = [];
/* The to do list and the form are displayed */
app.get('/todo', function (req, res) {
res.render('todo.ejs', {
todolist,
clickHandler: "func1();"
});
})
/* Adding an item to the to do list */
.post('/todo/add/', function (req, res) {
// Escapes HTML special characters in attribute values as HTML entities
let newTodo = sanitizer.escape(req.body.newtodo);
if (req.body.newtodo != '') {
todolist.push(newTodo);
}
res.redirect('/todo');
})
/* Deletes an item from the to do list */
.get('/todo/delete/:id', function (req, res) {
if (req.params.id != '') {
todolist.splice(req.params.id, 1);
}
res.redirect('/todo');
})
// Get a single todo item and render edit page
.get('/todo/:id', function (req, res) {
let todoIdx = req.params.id;
let todo = todolist[todoIdx];
if (todo) {
res.render('edititem.ejs', {
todoIdx,
todo,
clickHandler: "func1();"
});
} else {
res.redirect('/todo');
}
})
// Edit item in the todo list
.put('/todo/edit/:id', function (req, res) {
let todoIdx = req.params.id;
// Escapes HTML special characters in attribute values as HTML entities
let editTodo = sanitizer.escape(req.body.editTodo);
if (todoIdx != '' && editTodo != '') {
todolist[todoIdx] = editTodo;
}
res.redirect('/todo');
})
/* Redirects to the to do list if the page requested is not found */
.use(function (req, res, next) {
res.redirect('/todo');
})
.listen(port, function () {
// Logging to console
console.log(`Todolist running on http://0.0.0.0:${port}`)
});
// Export app
module.exports = app;
3. Package.Json File
{
"name": "my-todolist",
"version": "0.1.0",
"dependencies": {
"body-parser": "^1.16.0",
"ejs": "^2.5.5",
"express": "^4.14.0",
"method-override": "^3.0.0",
"sanitizer": "^0.1.3"
},
"scripts": {
"start": "node app.js",
"test": "mocha --recursive --exit",
"sonar": "sonar-scanner"
},
"author": "riaan@entersekt.com",
"description": "Basic to do list exercise",
"devDependencies": {
"chai": "^4.2.0",
"mocha": "^6.2.1",
"nyc": "^14.1.1",
"supertest": "^4.0.2"
}
}
4. test.js File
// Requiring module
const assert = require('assert');
// We can group similar tests inside a describe block
describe("Simple Calculations", () => {
before(() => {
console.log( "This part executes once before all tests" );
});
after(() => {
console.log( "This part executes once after all tests" );
});
// We can add nested blocks for different tests
describe( "Test1", () => {
beforeEach(() => {
console.log( "executes before every test" );
});
it("Is returning 5 when adding 2 + 3", () => {
assert.equal(2 + 3, 5);
});
it("Is returning 6 when multiplying 2 * 3", () => {
assert.equal(2*3, 6);
});
});
describe("Test2", () => {
beforeEach(() => {
console.log( "executes before every test" );
});
it("Is returning 4 when adding 2 + 3", () => {
assert.equal(2 + 3, 5);
});
it("Is returning 8 when multiplying 2 * 4", () => {
assert.equal(2*4, 8);
});
});
});
Git Hub File Link:
Jenkins Setup Run Node-todo-app Project:
First Step login start your Machine go to cmd Prompt
Check the Status your Jenkins Status is running or not
Copy your public IP in EC2 and add port 8080 , Paste to the browser.
Enter the user name and login the Jenkins
After that click the create a job and fill the requirements!
Enter tha node-todo-app name and select the Freestyle Project and click the ok button. After that
Type the Description (This is Simple Freestyle Basic Node-Todo-App), After that select the Github project, and paste the url
After that go to sorce code management and select the git , paste the github url and add the Credentials, Why we need Credentials if your repository is private you need the credentials so How to add the credentials.First Step is go to ubuntu machine and type ssh-keygen and genrate Public and private key
After that go the .ssh folder and see you have id_rsa and id_rsa.pub key.
id_rsa is your private key and id_rsa.pub is your public key. so we need to do go to github setting and add SSH and GPG key, Where we find, So what we need to do go to ubuntu machine and type cat id_rsa.pub, you will see public key so copy the public key and paste to github setting SSH and GPG key section.
Now we have add public key in github, After that go to jenkins, go to source code management , click to git,paste the your repository (node-todo-app ) url , add the condition click to add button and fill the form.
So we need to add private key so go to ubuntu machine type cat id_rsa
So that provide me private key copy the full private key , go the jenkins credentials after that go private section , add private key and click to Add button .
After that go to the Build Triggers option and selet the GitHub hook trigger for GITScm polling for webhook!
Webhook:
A webhook is a mechanism that allows one system or application to send real-time data to another system or application as soon as an event occurs. It is a way for different software applications to communicate with each other by triggering automatic data exchanges.
So now we need run the file so first step is need to go jenkins , go to the node-todo-app and click to configure button. After that go to the build step senction , Select the Execute Shell and type the command to run the node-todo-app project.
Click to save button and click to build now button.
Now we have green right so it is mean every thin is fine, go to consol output check!
Now we need go to EC2 machine , go to security group Section, go to inbound rules add 8000 port Number
After that copy to Ec2 public id and paste to chrom browser include 8000 port number
now you see node-todo-app running.