DevSecOps Project using Jenkins

This guide will help you set up a comprehensive DevSecOps CI/CD pipeline for a Node.js application using Jenkins. The pipeline will integrate code quality checks, security scanning, and Docker image vulnerability analysis.
Tools Required:
GitHub: For source code repository and version control.
Docker & Docker Compose: For containerizing the Node.js application.
Jenkins: For managing the CI/CD pipeline.
SonarQube: For continuous inspection of code quality.
OWASP Tools: For identifying security vulnerabilities.
Trivy: For scanning Docker images for vulnerabilities.

Below is the flow you can check

Requirements:
To follow this guide, you'll need an Amazon EC2 instance. We recommend using a t2.large instance for optimal performance.
1. Launch an EC2 Instance:
Go to the AWS Management Console.
Navigate to the EC2 Dashboard.
Click "Launch Instance."
Choose the Amazon Machine Image (AMI), such as Ubuntu 20.04 LTS.
Select the instance type t2.large (2 vCPUs, 8 GB RAM).
Configure instance details, add storage, and configure security groups (open ports 8080, 9000, and 80).
Review and launch the instance.
With this setup, you can proceed to install Jenkins, Docker, SonarQube, OWASP tools, and Trivy, as detailed in the guide.

Install Jenkins:
On Ubuntu:
sudo apt update sudo apt install openjdk-11-jdk 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.list.d/jenkins.list' sudo apt update sudo apt install jenkins sudo systemctl start jenkins sudo systemctl enable jenkinsAccess Jenkins at
http://your_server_ip:8080and follow the setup instructions.

Adding Docker and Docker Compose steps:
Install Docker & Docker Compose:
bsudo apt-get install -y docker.io docker-compose
Add User to Docker Group:
sudo usermod -aG docker $USER sudo usermod -aG docker jenkins

Creating a Jenkins Job for Node.js CI/CD
Open Jenkins Dashboard:
- Navigate to your Jenkins instance in a web browser.
Create New Job:
Click on "New Item".
Enter
node-to-cicdas the job name.Select "Pipeline" and click "OK".
Configure the Pipeline:
Under "Pipeline", select "Github Project".
Enter the GitHub repository URL:
https://github.com/GunjanGB/node-todo-cicd.git.
Save and Apply:
- Click "Save" to create the job.

Understanding SonarQube and Its Checks
SonarQube Overview: SonarQube is an open-source platform for continuous inspection of code quality. It performs automatic reviews to detect bugs, code smells, and security vulnerabilities in your codebase. By integrating SonarQube into your CI/CD pipeline, you can ensure your code maintains high quality and adheres to industry standards.
SonarQube Checks:
Code Quality:
Bugs: Identify potential errors that might cause unexpected behavior.
Vulnerabilities: Detect security risks that could be exploited by attackers.
Code Smells: Highlight maintainability issues and poor coding practices.
Coverage:
- Test Coverage: Measure the percentage of code executed during testing to ensure sufficient test coverage.
Duplications:
- Duplicate Code: Detect identical or similar blocks of code to reduce redundancy and improve maintainability.
Complexity:
- Cyclomatic Complexity: Measure the complexity of the code to identify high-risk areas that might require refactoring.
Documentation:
- Comments: Ensure adequate documentation of the code to enhance readability and maintainability.

Install SonarQube:
Run SonarQube in Docker:
docker run -itd --name sonar-qube-server -p 9000:9000 sonarqube:lts-communityAccess SonarQube at
http://your_server_ip:9000and follow the setup instructions.

When you login for the first time use :
User Id :admin
Password:admin

Adding a Jenkins User to SonarQube
To integrate SonarQube with Jenkins, you need to create a user in SonarQube and generate a token for Jenkins to use. Here’s a step-by-step guide:
Log in to SonarQube:
Open your SonarQube dashboard in a web browser.
Log in with your admin credentials.
Create a New User for Jenkins:
Navigate to Administration > Security > Users.
Click on Create User.
Fill in the required fields (Username, Name, Email, and Password).
Generate a Token:
Log in as the newly created Jenkins user.
Navigate to My Account > Security.
Click on Generate Tokens.
Provide a name for the token (e.g.,
jenkins-token).Click Generate and copy the token.
Add the Token to Jenkins:
Open your Jenkins dashboard in a web browser.
Navigate to Manage Jenkins > Manage Credentials > (global) > Add Credentials.
Select Secret text for the Kind.
Paste the token in the Secret field.
Set an ID and Description (e.g., Jenkins).
Click OK.



Step-by-Step Guide to Add SonarQube Scanner Plugin to Jenkins and Configure Credentials
Step 1: Install the SonarQube Scanner Plugin
Log in to Jenkins:
- Open your Jenkins instance in a web browser and log in with your credentials.
Navigate to Plugin Management:
- From the Jenkins dashboard, go to
Manage Jenkins>Manage Plugins.
- From the Jenkins dashboard, go to
Install SonarQube Scanner Plugin:
In the
Availabletab, search for "SonarQube Scanner".Check the box next to
SonarQube Scannerand click onInstall without restartorDownload now and install after restart.


Step 3: Add SonarQube Credentials
Navigate to Manage Credentials:
- Go to
Manage Jenkins>Manage Credentials.
- Go to
Add New Credentials:
Select the appropriate domain (e.g.,
Global).Click on
Add Credentialson the left sidebar.In the
Kinddropdown, selectSecret Textif you have a token, orUsername with passwordif you have user credentials.Fill in the required fields:
Secret Text: Enter the SonarQube token.
Username with Password: Enter the SonarQube username and password.
Provide an ID and description for easy identification (e.g.,
sonarqube-tokenorsonarqube-credentials).Click
OK.
Link Credentials to SonarQube Server:
Return to
Manage Jenkins>Configure System.In the
SonarQube Serverssection, select the credentials you added from theServer authentication tokendropdown.Save the configuration.


Step-by-Step Guide to Add Docker Credentials in Jenkins
Step 1: Navigate to Manage Credentials
Log in to Jenkins:
- Open your Jenkins instance in a web browser and log in with your credentials.
Navigate to Manage Credentials:
- From the Jenkins dashboard, go to
Manage Jenkins>Manage Credentials.
- From the Jenkins dashboard, go to
Step 2: Add Docker Credentials
Select the Appropriate Domain:
- Select the domain where you want to add the credentials (e.g.,
Global).
- Select the domain where you want to add the credentials (e.g.,
Add New Credentials:
Click on
Add Credentialson the left sidebar.In the
Kinddropdown, selectUsername with password.Fill in the required fields:
Username: Enter your Docker registry username.
Password: Enter your Docker registry password.
Provide an ID and description for easy identification (e.g.,
docker-registry-credentials).Click
OK.
Step 3: Use Docker Credentials in a Jenkins Job
Create or Configure a Jenkins Job:
- Go to your Jenkins dashboard and create a new job or configure an existing one.
Add Docker Registry Credentials to Job:
In the job configuration page, scroll down to the
Build Environmentsection.Check
Use secret text(s) or file(s).Click
Addand selectUsername with password.Select the Docker credentials you added from the dropdown list.

Step : Configure SonarQube in Jenkins
Navigate to Global Tool Configuration:
- Go to
Manage Jenkins>Global Tool Configuration.
- Go to
Add SonarQube Scanner:
Scroll down to the
SonarQube Scannersection and clickAdd SonarQube Scanner.Provide a name (e.g.,
SonarQube Scanner).




Add Webhook to SonarQube
Log in to SonarQube:
- Open your SonarQube instance in a web browser and log in with your credentials.
Navigate to Webhooks:
Go to the
Administrationtab.In the left sidebar, under
Configuration, click onWebhooks.
Create a New Webhook:
Click on
Create.Fill in the required fields:
Name: Give your webhook a descriptive name (e.g.,
Jenkins Webhook).URL: Enter the Jenkins webhook URL you obtained earlier (e.g.,
http://<jenkins-server>/sonarqube-webhook/).
Save the Webhook:
- Click
Saveto create the webhook.
- Click


By following these steps, you have integrated SonarQube with Jenkins for the node-todo-cicd repository and successfully obtained the analysis results. The results can be viewed on the SonarQube project dashboard, providing insights into code quality and potential issues.


TRIVY
Step-by-Step Guide to Install and Use Trivy with Docker
Trivy is a comprehensive and easy-to-use security tool for scanning container images for vulnerabilities. This guide will help you install Trivy using Docker and run a continuous watch on a Docker image.
To install trivy use the commands documentation : TRIVY installation


OUTPUT

Trivy is an open-source vulnerability scanner for container images and other artifacts. It quickly detects security issues in operating system packages, application dependencies, and infrastructure as code (IaC) files. Trivy is easy to integrate into CI/CD pipelines, making it a valuable tool for maintaining secure software development practices. It supports scanning Docker images, local file systems, and Git repositories, providing comprehensive security insights to help developers identify and mitigate potential risks early in the development lifecycle.
OWASP :
Step-by-Step Guide to Add the OWASP Dependency-Check Plugin to Jenkins
The OWASP Dependency-Check Plugin is a valuable tool for identifying vulnerabilities in your project's dependencies. This guide will walk you through adding and configuring this plugin in Jenkins, assuming Jenkins is already installed on your system.
Step 1: Install the OWASP Dependency-Check Plugin
Access Jenkins Dashboard: Open your web browser and navigate to your Jenkins instance (e.g.,
http://localhost:8080).Navigate to Plugin Manager:
Click on
Manage Jenkinsfrom the left-hand side menu.Select
Manage Plugins.
Note : For the first time it might take up to 20 - 30 minutes to install. But next time it will run in few seconds
Install OWASP Dependency-Check Plugin:
Click on the
Availabletab.In the search box, type
OWASP Dependency-Check.Check the box next to the
OWASP Dependency-Check Plugin.Click on
Install without restartorDownload now and install after restartbased on your preference.

Step 2: Configure the Plugin
Access Global Tool Configuration:
Go back to the
Manage Jenkinspage.Click on
Global Tool Configuration.
Add Dependency-Check Installation:
Scroll down to the
OWASP Dependency-Checksection.Click on
Add Dependency-Check.Give it a name (e.g.,
OWASP).Set the installation method (Install automatically is typically selected).
Click
Save.

Output after the code run :


Groovy Syntax for Jenkins DevSecOps Pipeline
pipeline {
agent any
environment{
SONAR_HOME = tool 'Sonar'
}
stages {
stage("code"){
steps{
git url: "https://github.com/GunjanGB/node-todo-cicd.git/", branch: "master"
}
}
stage("SonarQube Analysis"){
steps{
withSonarQubeEnv("Sonar"){
sh " $SONAR_HOME/bin/sonar-scanner -DSonar.projectName=notetodo -DSonar.projectKey=notetodo "
}
}
}
stage("SonarQube Quality Gates"){
steps{
timeout(time:1, unit : "MINUTES"){
waitForQualityGate abortPipeline : false
}
}
}
stage("build and test"){
steps{
sh "docker build -t node-app:latest ."
}
}
stage("Trivy"){
steps{
sh "trivy image node-app"
}
}
stage("OWASP"){
steps{
dependencyCheck additionalArguments: '--scan ./', odcInstallation: 'OWASP'
dependencyCheckPublisher pattern: '**/dependency-check-report.xml'
}
}
stage("push"){
steps{
withCredentials([usernamePassword(credentialsId:"DockerHubCreds",passwordVariable:"dockerHubPass",usernameVariable:"dockerHubUser")]){
sh "docker login -u ${env.dockerHubUser} -p ${env.dockerHubPass}"
sh "docker tag node-app:latest ${env.dockerHubUser}/node-app:latest"
sh "docker push ${env.dockerHubUser}/node-app:latest"
}
}
}
stage('Deploy') {
steps {
sh 'docker compose down'
sh 'docker compose up -d'
}
}
}
}
IMAGE :

Jenkins DevSecOps Pipeline Output

Step-by-Step guide to setting up a Jenkins DevSecOps pipeline using the provided GitHub repository:
Step : Create a Jenkins Pipeline Job
From the Jenkins Dashboard, click your project
node-to-cicd.Go to Configuration
Under
SCM, selectGit.Enter the repository URL:
https://github.com/GunjanGB/node-todo-cicd.git.Set the
Branch Specifierto*/masteror the desired branch.

You can see the output in stages that now the code is being taken from SCM

To set up a webhook in GitHub to automate Jenkins builds for the repository https://github.com/GunjanGB/node-todo-cicd.git, follow these steps:
Step 1: Create a Webhook in GitHub
Go to your GitHub repository:
- Navigate to
https://github.com/GunjanGB/node-todo-cicd.
- Navigate to
Open repository settings:
- Click on the
Settingstab.
- Click on the
Add a webhook:
In the left sidebar, click on
Webhooks.Click the
Add webhookbutton.
Configure the webhook:
Payload URL: Enter your Jenkins webhook URL. It typically looks like
http://your-jenkins-server/github-webhook/.Content type: Keep it as it is .
Secret: You can leave this empty or set a secret token (optional).
Which events would you like to trigger this webhook? Choose
Just the push event.Active: Ensure the webhook is active.
Save the webhook:
- Click the
Add webhookbutton.
- Click the

Step 2: Test the Webhook
Push a change to the repository:
- Make a simple change in the repository, commit, and push it to the GitHub repository.
Verify Jenkins build:
- Go to your Jenkins dashboard and observe that the pipeline job is triggered automatically due to the webhook.
By following these steps, your Jenkins pipeline will be triggered automatically whenever there's a push to the https://github.com/GunjanGB/node-todo-cicd.git repository. This setup helps in continuous integration by automating the build process upon each code change.

Made the changes to code as you can see Made for Batch 7 has changed to Made for DevOps Enthusiasts ! and this changes were automatically deployed using Jenkins CICD pipeline .
You can confirm it below as well in stages feature of Jenkins

Conclusion
By following the steps outlined in this guide, you have successfully set up a Jenkins pipeline that integrates DevSecOps principles for the https://github.com/GunjanGB/node-todo-cicd.git repository. The process includes:
Installing and Configuring Jenkins Plugins: Ensuring Jenkins is equipped with the necessary tools for SCM, code quality analysis, security checks, and deployment.
Configuring Global Tools and SonarQube Integration: Setting up essential tools and connecting Jenkins with SonarQube for static code analysis.
Creating a Jenkins Pipeline: Defining a
Jenkinsfilethat automates the stages of checking out code, installing dependencies, performing static code analysis, running security checks, testing, building, and deploying the application.Adding a GitHub Webhook: Automating the Jenkins pipeline by triggering builds through GitHub webhooks on code changes.
This comprehensive pipeline ensures that each code change undergoes rigorous quality and security checks before being built and deployed, adhering to the principles of DevSecOps. The successful deployment of the application using Jenkins signifies a robust and automated CI/CD process, integrating tools like SonarQube, Trivy, OWASP Dependency-Check, and other security plugins.
By implementing this setup, you achieve a continuous and secure delivery process, enhancing the quality, security, and reliability of your application deployments.
Feel free to reach out with any questions or thoughts in the comments below. Happy DevOps-ing! 🚀




