# Jenkins (DevSecOps)

# DevSecOps Pipeline Setup

## **Prerequisites for DevSecOps**

### **Required Tools:**

* Jenkins with Java
    
* Docker
    
* Docker Compose
    
* SonarQube
    
* Trivy
    
* Scout
    
* OWASP Dependency Checker
    
* ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1738183887079/22a81f9c-c436-4271-a8af-951f8e811288.png align="center")
    

We will use all these tools for a DevSecOps pipeline setup. It is recommended to use an **EC2 instance with at least t2.large** to avoid performance lag.

---

### **Step 1: Set Up Jenkins, Docker, and Docker Compose**

1. Install and configure Jenkins.
    
2. Install Docker and Docker Compose.
    
3. Add Jenkins and your user to the Docker group:
    
    ```plaintext
    bashCopyEditsudo usermod -aG docker $USER  
    sudo usermod -aG docker jenkins  
    sudo systemctl enable docker  
    ```
    

Now both Jenkins and Docker are set up and running.

---

### **Step 2: SonarQube Setup**

#### **What is SonarQube?**

SonarQube has two main components:

* **SonarQube Scanner:** Located in Jenkins, it scans the code and sends a compressed report to the SonarQube server.
    
* **SonarQube Server:** Processes the report to identify vulnerabilities, code smells, and code coverage.
    

#### **SonarQube Features:**

* Detects bugs and vulnerabilities.
    
* Checks for code smells (bad practices).
    
* Ensures the code passes quality gates based on defined programming rules.
    

#### **SonarQube Setup:**

Run SonarQube using Docker:

```plaintext
bashCopyEditdocker run -itd --name sonarqube-server -p 9000:9000 sonarqube:lts-community  
docker ps  
```

Access SonarQube at `http://<IP>:9000`. Use the default credentials `admin/admin`, then create a custom password.

---

### **SonarQube and Jenkins Integration**

1. Generate a Personal Access Token (PAT) for Jenkins in SonarQube under **Administration &gt; Security**.
    
2. Store this token in Jenkins Credentials as a **Secret Text**.
    
    * **Manage Jenkins &gt; Credentials &gt; Global &gt; Add Credentials:**
        
        * **Secret:** Paste the SonarQube PAT
            
        * **ID:** Sonar
            
        * **Description:** Sonar
            
3. Install the **SonarQube Scanner Plugin** in Jenkins.
    
4. Configure SonarQube in Jenkins under **Manage Jenkins &gt; Configure System:**
    
    * Name: Sonar
        
    * URL: `<SonarQube URL>`
        
    * Server Authentication Token: Select the stored token.
        
5. Add SonarQube Scanner under **Global Tool Configuration:**
    
    * Name: Sonar
        
    * Install automatically: Select the required version.
        

#### **Webhook Configuration:**

Set up a webhook in SonarQube to notify Jenkins about the analysis results:

* Go to **Administration &gt; Configuration &gt; Webhooks**
    
* Create a webhook with the Jenkins URL:
    
    ```plaintext
    arduinoCopyEdithttp://<Jenkins-IP>:8080/sonarqube-webhook  
    ```
    

---

### **Jenkins Pipeline Configuration**

#### **Node.js DevSecOps Pipeline Job Setup**

```plaintext
groovyCopyEditpipeline {
    agent any

    environment {
        SONAR_HOME = tool "Sonar"
    }

    stages {
        stage('Checkout') {
            steps {
                git url: 'https://github.com/vaseem143/django-proj.git', branch: 'main'
                echo 'Code successfully cloned!'
            }
        }

        stage('Build & Test') {
            steps {
                sh 'docker build -t node-app:latest .'
            }
        }

        stage('SonarQube Analysis') {
            steps {
                withSonarQubeEnv("Sonar") {
                    sh "$SONAR_HOME/bin/sonar-scanner -Dsonar.projectName=node-to-do -Dsonar.projectKey=node -X"
                }
            }
        }

        stage('SonarQube Quality Gates') {
            steps {
                timeout(time: 1, unit: "MINUTES") {
                    waitForQualityGate abortPipeline: true
                }
            }
        }

        stage('OWASP Dependency Check') {
            steps {
                dependencyCheck additionalArguments: '--scan ./', odcInstallation: 'Owasp'
                dependencyCheckPublisher pattern: '**/dependency-check-report.xml'
            }
        }

        stage('Trivy Security Scan') {
            steps {
                sh 'trivy image node-app:latest'
            }
        }

        stage('Push to Docker Repository') {
            steps {
                withCredentials([usernamePassword(credentialsId: 'DockerHubCreds', passwordVariable: 'dockerPass', userVariable: 'dockerUser')]) {
                    sh 'docker login -u $dockerUser -p $dockerPass'
                    sh 'docker tag node-app:latest $dockerUser/node-app:latest'
                    sh 'docker push $dockerUser/node-app:latest'
                }
            }
        }

        stage('Deploy') {
            steps {
                sh 'docker compose up -d'
            }
        }

        stage('Email Notification') {
            steps {
                echo 'Sending email notification...'
            }
        }
    }
}
```

---

### **Security Tools Setup**

#### **Trivy**

Trivy is an image scanning tool used to identify vulnerabilities.

* Install Trivy:
    
    ```plaintext
    bashCopyEditsudo apt install trivy  
    ```
    
* Scan an image:
    
    ```plaintext
    bashCopyEdittrivy image <image_name>  
    ```
    

#### **OWASP Dependency Checker**

OWASP Dependency Checker helps detect known vulnerabilities in project dependencies.

* Install the OWASP Dependency Check plugin in Jenkins and restart Jenkins.
    
* Configure the tool under **Global Tool Configuration:**
    
    * Name: Owasp
        
    * Install automatically: Select the required version.
        

This setup completes the DevSecOps pipeline configuration. Ensure each tool is properly configured to maintain a secure and efficient build process.  
ṣ

First - setup the jenkins , then docker and docker-compose

* sudo usermod -aG docker $USER
    
* sudo usermod -aG docker jenkins
    
* sudo systemctl enable docker - so now jenkins and docker is running now we require sonarqube server so i need to setup the sonarqube server
    

What is sonarqube server

* we need to understand 2 componenets one is scanner and server
    
* flow is sonar scanner is in jenkins takes teh ecode and scan and send to sonarqube server in compressed format , so in sonarqube scanner multiple things happens check vulnerabilities , code coverage : 10 lines of code is tested means 100 percent code coverage
    
* code smell bakwas code checks , quality gate also be there it means
    
    sonarqube there is a every programming rules are there if the code has been passed quality with that rules then code will be passed
    

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1738184792160/70543d21-fe96-410f-b73f-32ddfc035198.png align="center")

docker run -itd —name sonarqube-server -p 9000:9000 sonarqube:lts-community

* docker ps
    
* ip:9000 , so initially its admin and admin then we can create our own custom password.
    
* you can see bugs , code smells , vulneraabilities so by using these rules sonarqube will generate the report
    
* under the code coverage we keep threshold coverage based on confditons if this conditions matche sthen threshold will e passed
    

will talk more about sonarqube , click on sonarqube or example we have a proj to scan directly we can scan from github , azure , bitbucket .

i dont want to scan from here i want to sed reports from snaner to thir server for this i need to create a user and have to give permission for jenkisn

* administartion , security
    
* if i want to give access for jenkins here in this i need to create a pat token so click on three dots and generate the sonartoken for jenkins
    
* copy and store it
    
* now i will integrate sonarqube with jenkins
    

**how can i integarte with jenkins**

* i will install the plugins called sonarplugin - install sonarqubescanner
    
* now i want to keep sonarque secrets in jekins , where could i keep in credentials
    
* * manage jenkins - credentials , click on that , global , add , secret -text , paste it here , give credentials id = Sonar , descriptions id : Sonar
        
        \* we needed sonar secret for sonarqube scanner now i want to link my sonar with jenkins i will go to the system , find sonarqube
        
        \* add sonarqube server - give name = Sonar , Give Url , Server authentication token =select secret
        
        \* we have connected our sonarquebe to jenkins . do it and save
        

now we need to install tools under tools section , - add sonaqrue scanner - Sonar - add installer select version click and save

WebHooks : what is webhooks

this is your sevre and another server lets say jenkins and sonarqube

* jenkins server ran some pipeline now jenkins sent code to sonarserver , how can jenkins knowsn sonarqube server sent report to jenkins , machines doesnt believe on trust they belive on acknowledgement
    
* we have webhooks , has url where will tell if my work has done send acknoledgment to this url
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1738186076682/253b6251-904d-46b8-8895-128a23665d25.png align="center")
    

same concept we have in gitub also like developer pushes to the code into github ten automatically jenkins pipeline should trigger in github we need to keep jenkins url then github tells code changed send acknoeledgement to jenkins .

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1738186225601/9845a34d-64e4-458f-8d1a-b4ad34cc2a82.png align="center")

now we will go and setup webhook , to whom we need t send that url we should give here - go to administration - configure , webhook - create - jenkins - url :ip:8080/sonarqube-webhook

* secret is not mandatory
    
* now will configure
    

Create a pipeline job for node-to do app

* description - this is a nodejs project , add github project select github-webhook - trigger
    

```plaintext
pipeline {
            agent any

         environment{
          SONAR_HOME= tool "Sonar"
}
            stages {
                stage('Checkout') {
                    steps {
                        git url: 'https://github.com/vaseem143/django-proj.git', branch: 'main'
                        echo 'Code successfully cloned!'
                    }
                }
                stage('Build & Test ') {
                    steps {
                        sh 'docker build -t node-app:latest .'
                    }
                }
                
                stage('SonarQube Analysis') {
                    steps {
                        withSonarQubeEnv("Sonar"){
                        sh "#SONAR_HOME/bin/sonar-scanner -Dsonar.projectName=node-to-do -D sonar.projectKey="node -X"
}
                   }
                }
               stage('SonarQube Gates') {
                    steps {
                        timeout(time: 1, unit: "MINUTES"{
                        waitForQualityGate abortPipeline: True (false)
                   }
                }
                stage('OWASP Dependency Check') {
                    steps {
                        dependencyCheck additionalArguments: '--scan ./' , odcInstallation: 'Owasp' 
                        dependencyCheckPublisher pattern: '**/dependency-check-report.xml'
                    }
                }
                stage('Trivy Security Scan') {
                    steps {
                        sh 'trivy image node-app:latest'
                    }
                }
               
                stage('Push to Docker Repository') {
                    steps {
                        withCredentials([usernamePassword(credentialsId: 'DockerHubCreds', passwordVariable: 'dockerPass', userVariable: 'dockerUser')]) {
                            sh 'docker login -u $dockerUser -p $dockerPass'
                            sh 'docker tag node-app:latest $dockerUser/node-app:latest'
                            sh 'docker push $dockerUser/node-app:latest'
                        }
                    }
                }
                
                stage('Deploy') {
                    steps {
                        sh 'docker compose up -d'
                    }
                }
                stage('Email Notification') {
                    steps {
                        echo 'Sending email notification...'
                    }
                }
            }
        }
```

* what is the sonartool name = Sonar , keep the environament and use this env under the stage of sonarqube analysis withSonarqubeEnv(“Sonar”)
    

and prepare the pipeline and run the pipeline .

\-Now we will talk about trivy

## Trivy

* trivy is a image scanning tool by which it scans the vulnerabilities
    
* trivy db reffers to the image and generate a report after scanning .
    
* install trivy , after trivy installation has been done then dcoker images
    
* trivy image image\_name
    

Now we will use Owasp Dependency Checker

* Owasp dependency checker is one org is having datase there we can use any library or any dependency somewhere long back it had got issued some , it is cached , so in owasp dependency checker will be there to check malicious , millesnous it checks , it detects the vulnerability
    
* if any dependency is making any issue we check with owasp dependency checker , either it scans from the internet actually owasp dependency will down and reduce the tome to check
    

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1738189342953/48e82d6e-2daa-41a3-8023-019501091f78.png align="center")

install plugin , owaspdependency check then restart then go to the tools section - name:Owasp

install from github : select the version
