# Netflix Clone CI/CD Pipeline | Jenkins | Docker | Kubernetes | Monitoring | DevSecOps

<figure><img src="/files/3f3Y7JM90l9juuo43Wic" alt=""><figcaption></figcaption></figure>

## **Step 1:Launch an Ubuntu(22.04) T2 Large Instance** <a href="#heading-step1launch-an-ubuntu2204-t2-large-instance" id="heading-step1launch-an-ubuntu2204-t2-large-instance"></a>

<figure><img src="/files/7PHN8fTDuadnyGrvr55s" alt=""><figcaption></figcaption></figure>

## **Step 2 — Install Jenkins, Docker and Trivy** <a href="#heading-step-2-install-jenkins-docker-and-trivy" id="heading-step-2-install-jenkins-docker-and-trivy"></a>

<figure><img src="/files/TCd7DOGGmkwP1cF6p95E" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/pgAKEmrCO8cXb3OZVZAX" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/p3tSj9pTjs2fV7jbGPXk" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/HQ8XkSyC0sZUXf7QMytX" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/K7Y59a76T6AbjBqqqbM2" alt=""><figcaption></figcaption></figure>

```

sudo apt-get install docker.io 
sudo usermod -aG docker ubuntu
newgrp docker

```

when we will run the pipeline , will get error so , we have to provide permission docker.sock

```
sudo chmod 777 /var/run/docker.sock
```

<figure><img src="/files/Cm3GfnmTONzpfrQwnWT7" alt=""><figcaption></figcaption></figure>

Installing the SonarQube -

```
docker run -d --name sonar -p 9000:9000 sonarqube:lts-community
```

<figure><img src="/files/mMKJvTUvtp7xMNtNkDPX" alt=""><figcaption></figcaption></figure>

```
username admin
password admin
```

<figure><img src="/files/jGubth1Ix10xksuJcSAp" alt=""><figcaption></figcaption></figure>

So , Now we are installing Trivy, which is used for Scanning the repository files and scan the Docker images&#x20;

#### Install Trivy <a href="#heading-2c-install-trivy" id="heading-2c-install-trivy"></a>

```
vi trivy.sh

```

```
sudo apt-get install wget apt-transport-https gnupg lsb-release -y
wget -qO - https://aquasecurity.github.io/trivy-repo/deb/public.key | gpg --dearmor | sudo tee /usr/share/keyrings/trivy.gpg > /dev/null
echo "deb [signed-by=/usr/share/keyrings/trivy.gpg] https://aquasecurity.github.io/trivy-repo/deb $(lsb_release -sc) main" | sudo tee -a /etc/apt/sources.list.d/trivy.list
sudo apt-get update
sudo apt-get install trivy -y

```

```
sudo chmod +x trivy.sh
bash trivy.sh
```

<figure><img src="/files/VbpIBuud5maNjNkDAJrI" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/aRm2N7TVxSk8rkDuBuMX" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/j28qCeVgq32DnFwlQAIj" alt="" width="377"><figcaption></figcaption></figure>

## Step 3: Create a TMDB API Key <a href="#heading-step-3-create-a-tmdb-api-key" id="heading-step-3-create-a-tmdb-api-key"></a>

&#x20;

<figure><img src="/files/W45PrpalcAv73bYBzb0c" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/tdFwTZSGx2GpNkJJlWkD" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/dNiNjYOcwTD9XDmU1j6F" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/h7oLJIXFJZ1G6HUXxsfS" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/bVXn6aWR8lHyvN1FJROt" alt=""><figcaption></figcaption></figure>

<br>

<figure><img src="/files/5oVDmYAOarz2RlyRcRLw" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/WIOfLwmW0zSEv5eBupAb" alt=""><figcaption></figcaption></figure>

## Step 4 — Install Prometheus and Grafana On the new Server <a href="#heading-step-4-install-prometheus-and-grafana-on-the-new-server" id="heading-step-4-install-prometheus-and-grafana-on-the-new-server"></a>

Creating prometheus user

```
sudo useradd \
    --system \
    --no-create-home \
    --shell /bin/false prometheus

```

<figure><img src="/files/dtClDGhyIg0fq7x0JM2I" alt="" width="336"><figcaption></figcaption></figure>

You can use the curl or wget command to download Prometheus.

```
wget https://github.com/prometheus/prometheus/releases/download/v2.47.1/prometheus-2.47.1.linux-amd64.tar.gz

```

<figure><img src="/files/GoBbbtRPBI6575HLFKXS" alt=""><figcaption></figcaption></figure>

Then, we need to extract all Prometheus files from the archive.

```
tar -xvf prometheus-2.47.1.linux-amd64.tar.gz

```

<figure><img src="/files/IiNYHDewrKsV9sCKhT48" alt=""><figcaption></figcaption></figure>

Create the directory for Prometheus

```
sudo mkdir -p /data /etc/prometheus

```

Now, let's change the directory to Prometheus and move some files.

```
cd prometheus-2.47.1.linux-amd64/

```

<figure><img src="/files/yudDC4WSXKxxbjBk0gBQ" alt=""><figcaption></figcaption></figure>

#### let's move the Prometheus binary and a promtool to the /usr/local/bin/. promtool is used to check configuration files and Prometheus rules.

```
sudo mv prometheus promtool /usr/local/bin/
sudo mv consoles/ console_libraries/ /etc/prometheus/

```

#### The main Prometheus configuration file.

```
sudo mv prometheus.yml /etc/prometheus/prometheus.yml
```

#### To avoid permission issues, you need to set the correct ownership for the /etc/prometheus/ and data directory.

```
sudo chown -R prometheus:prometheus /etc/prometheus/ /data/

```

<figure><img src="/files/Bu5XfD9BpGabha34VLVI" alt=""><figcaption></figcaption></figure>

#### You can delete the archive and a Prometheus folder when you are done.

```
cd
rm -rf prometheus-2.47.1.linux-amd64.tar.gz
```

<figure><img src="/files/whnbrSy99CjaKtmPjMf5" alt=""><figcaption></figcaption></figure>

#### Verify that you can execute the Prometheus binary by running the following command:

```

prometheus --version
```

<figure><img src="/files/yip9hPAV2ATDYtbZunWb" alt=""><figcaption></figcaption></figure>

#### To get more information and configuration options, run Prometheus Help.

```
prometheus --help

```

#### We're going to use Systemd, which is a system and service manager for Linux operating systems. For that, we need to create a Systemd unit configuration file.

```
sudo vim /etc/systemd/system/prometheus.service

```

**Prometheus.service**&#x20;

<figure><img src="/files/6eIVBzfouF39wGecO7xS" alt=""><figcaption></figcaption></figure>

```
[Unit]
Description=Prometheus
Wants=network-online.target
After=network-online.target

StartLimitIntervalSec=500
StartLimitBurst=5

[Service]
User=prometheus
Group=prometheus
Type=simple
Restart=on-failure
RestartSec=5s
ExecStart=/usr/local/bin/prometheus \
  --config.file=/etc/prometheus/prometheus.yml \
  --storage.tsdb.path=/data \
  --web.console.templates=/etc/prometheus/consoles \
  --web.console.libraries=/etc/prometheus/console_libraries \
  --web.listen-address=0.0.0.0:9090 \
  --web.enable-lifecycle

[Install]
WantedBy=multi-user.target

```

```
sudo systemctl enable prometheus
sudo systemctl start prometheus
sudo systemctl status prometheus

```

<figure><img src="/files/itMbFOsuP7YIAAaebHWd" alt=""><figcaption></figcaption></figure>

#### If , you encounter any issues with Prometheus or are unable to start it. The easiest way to find the problem is to use the journalctl command and search for errors.

```
journalctl -u prometheus -f --no-pager

```

#### Now we can try to access it via the browser. I'm going to be using the IP address of the Ubuntu server. You need to append port 9090 to the IP.

```
<public-ip:9090>

```

<figure><img src="/files/LBmrguU0BYgR7h4TSYio" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/zOsmJSAI54WnQNPQupDz" alt=""><figcaption></figcaption></figure>

### Install Node Exporter on Ubuntu 22.04 <a href="#heading-install-node-exporter-on-ubuntu-2204" id="heading-install-node-exporter-on-ubuntu-2204"></a>

First, let's create a system user for Node Exporter by running the following command:

```
sudo useradd \
    --system \
    --no-create-home \
    --shell /bin/false node_exporter

```

<figure><img src="/files/oz02QwtVt86Cpdhb8Yin" alt="" width="375"><figcaption></figcaption></figure>

```
wget https://github.com/prometheus/node_exporter/releases/download/v1.6.1/node_exporter-1.6.1.linux-amd64.tar.gz

```

<figure><img src="/files/Iollit5DGuOMbPXAEKeK" alt=""><figcaption></figcaption></figure>

Extract the node exporter from the archive.

```
tar -xvf node_exporter-1.6.1.linux-amd64.tar.gz

```

<figure><img src="/files/MVAo9PVuXfnXHLAPtieb" alt=""><figcaption></figcaption></figure>

Move binary to the /usr/local/bin.

```
sudo mv \
  node_exporter-1.6.1.linux-amd64/node_exporter \
  /usr/local/bin/

```

Clean up, and delete node\_exporter archive and a folder.<br>

```
rm -rf node_exporter*

```

<figure><img src="/files/ot1tAe2XwR2VrUUEfXyH" alt=""><figcaption></figcaption></figure>

Verify that you can run the binary.<br>

```
node_exporter --version

```

<figure><img src="/files/qK82ykweDcCV08yhecMH" alt=""><figcaption></figcaption></figure>

Node Exporter has a lot of plugins that we can enable. If you run Node Exporter help you will get all the options.

```
node_exporter --help

```

Next, create a similar systemd unit file.

```
sudo vim /etc/systemd/system/node_exporter.service

```

**node\_exporter.service**

<figure><img src="/files/PckpaLcovGKiSzhDIsWt" alt=""><figcaption></figcaption></figure>

```
[Unit]
Description=Node Exporter
Wants=network-online.target
After=network-online.target

StartLimitIntervalSec=500
StartLimitBurst=5

[Service]
User=node_exporter
Group=node_exporter
Type=simple
Restart=on-failure
RestartSec=5s
ExecStart=/usr/local/bin/node_exporter \
    --collector.logind

[Install]
WantedBy=multi-user.target

```

```
sudo systemctl enable node_exporter
sudo systemctl start node_exporter
sudo systemctl status node_exporter

```

<figure><img src="/files/WfEyQvzwGxiTKZe2w25m" alt=""><figcaption></figcaption></figure>

#### If you have any issues, check logs with journalctl

```
journalctl -u node_exporter -f --no-pager

```

### To create a static target, you need to add job\_name with static\_configs.

```
sudo vim /etc/prometheus/prometheus.yml

```

<figure><img src="/files/OXTqFSplSzmqyxzJQzOJ" alt="" width="556"><figcaption></figcaption></figure>

### **prometheus.yml**

```
  - job_name: node_export
    static_configs:
      - targets: ["localhost:9100"]

```

<figure><img src="/files/mWHbTOThVO8sJxKhMg6G" alt=""><figcaption></figcaption></figure>

By default, Node Exporter will be exposed on port 9100.

Since we enabled lifecycle management via API calls, we can reload the Prometheus config without restarting the service and causing downtime.

Before, restarting check if the config is valid.

```
promtool check config /etc/prometheus/prometheus.yml

```

<figure><img src="/files/gUvlKY4lv5OYjxwSBcz9" alt=""><figcaption></figcaption></figure>

Then, you can use a POST request to reload the config.

```
curl -X POST http://localhost:9090/-/reload

```

<figure><img src="/files/MSOCKdbs8bj6GlR78Hwd" alt="" width="563"><figcaption></figcaption></figure>

Check the targets section

```
http://<ip>:9090/targets
```

<figure><img src="/files/OeTUBv5KlSHXLMdC1Iq6" alt=""><figcaption></figcaption></figure>

### Install Grafana on Ubuntu 22.04 <a href="#heading-install-grafana-on-ubuntu-2204" id="heading-install-grafana-on-ubuntu-2204"></a>

First, let's make sure that all the dependencies are installed.

```
sudo apt-get install -y apt-transport-https software-properties-common

```

<figure><img src="/files/OiA00Zkxr5yeHpt2rOfZ" alt=""><figcaption></figcaption></figure>

Next, add the GPG key.

```
wget -q -O - https://packages.grafana.com/gpg.key | sudo apt-key add -

```

Add this repository for stable releases.<br>

```
echo "deb https://packages.grafana.com/oss/deb stable main" | sudo tee -a /etc/apt/sources.list.d/grafana.list

```

<figure><img src="/files/BhSasFzYS5sviK8zpmqa" alt=""><figcaption></figcaption></figure>

After you add the repository, update and install Garafana.

```
sudo apt-get update
sudo apt-get -y install grafana

```

<figure><img src="/files/5kLm3I1W8mwmV19EFkXy" alt=""><figcaption></figcaption></figure>

To automatically start the Grafana after reboot, enable the service.

```
sudo systemctl enable grafana-server
sudo systemctl start grafana-server
sudo systemctl status grafana-server

```

<figure><img src="/files/AB784foESrxzDINgkIJ2" alt=""><figcaption></figcaption></figure>

#### Go to `http://<ip>:3000` and log in to the Grafana using default credentials. The username is admin, and the password is admin as well.

```
username admin
password admin

```

<figure><img src="/files/9ypxYbQ64ymCI3Usarli" alt=""><figcaption></figcaption></figure>

To visualize metrics, you need to add a data source first.

<figure><img src="/files/GXG9BfTCldr1j1vSxRSz" alt=""><figcaption></figcaption></figure>

Click Add data source and select Prometheus.

<figure><img src="/files/SoGxFkbGwbbVrapJ22Qm" alt=""><figcaption></figcaption></figure>

#### For the URL, enter [**localhost:9090**](http://localhost:9090/) and click Save and test. You can see Data source is working.

<figure><img src="/files/7gtTEj9EKusAl7PG6Cuu" alt=""><figcaption></figcaption></figure>

Click on Save and Test.

<figure><img src="/files/7OXeHxuSyEBNJds8GeRG" alt=""><figcaption></figcaption></figure>

Let's add Dashboard for a better view

<figure><img src="/files/oPUsESYepnq5dU3DK5cQ" alt=""><figcaption></figcaption></figure>

Click on Import Dashboard paste this code 1860 and click on load

<figure><img src="/files/iYuIhS7kOptnYk4MLkck" alt=""><figcaption></figcaption></figure>

Select the Datasource and click on Import

<figure><img src="/files/V8HYPDlBHKFlN0RmRRTw" alt=""><figcaption></figcaption></figure>

### You will see this output

<figure><img src="/files/ql8NyYtVqdZWdoiNgsxT" alt=""><figcaption></figcaption></figure>

## Step 5 — Install the Prometheus Plugin and Integrate it with the Prometheus server <a href="#heading-step-5-install-the-prometheus-plugin-and-integrate-it-with-the-prometheus-server" id="heading-step-5-install-the-prometheus-plugin-and-integrate-it-with-the-prometheus-server"></a>

Let's Monitor JENKINS SYSTEM

Need Jenkins up and running machine

Goto Manage Jenkins --> Plugins --> Available Plugins

<figure><img src="/files/tGTwAmT08kZDq3vfLwKy" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/DEDnWlfa3KyTCl1b2qK8" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/YIcfD8lMP9dnBzkYJHJS" alt=""><figcaption></figcaption></figure>

Once that is done you will Prometheus is set to `/Prometheus` path in system configurations

<figure><img src="/files/KR0b91Z5GGHqZtt2BPMp" alt=""><figcaption></figcaption></figure>

Nothing to change click on apply and save

To create a static target, you need to add job\_name with static\_configs. go to Prometheus server

```
sudo vim /etc/prometheus/prometheus.yml

```

Paste below code

```
  - job_name: 'jenkins'
    metrics_path: '/prometheus'
    static_configs:
      - targets: ['<jenkins-ip>:8080']

```

<figure><img src="/files/vk1B5AyhGXLgJZzeAZj6" alt=""><figcaption></figcaption></figure>

Before, restarting check if the config is valid.

```
promtool check config /etc/prometheus/prometheus.yml
```

<figure><img src="/files/Zwdmaeh82AmiNVPmbPGw" alt=""><figcaption></figcaption></figure>

Then, you can use a POST request to reload the config.

```
curl -X POST http://localhost:9090/-/reload

```

Check the targets section

```
http://<ip>:9090/targets

```

<figure><img src="/files/JFpnrJhQErJWWudGX60T" alt=""><figcaption></figcaption></figure>

Let's add Dashboard for a better view in Grafana

Click On Dashboard --> + symbol --> Import Dashboard

Use Id `9964` and click on load

<figure><img src="/files/IyTqugWJYhJvuXBd6MNW" alt=""><figcaption></figcaption></figure>

Select the data source and click on Import

<figure><img src="/files/yNv9P7uWS9O3kKepVmlL" alt=""><figcaption></figcaption></figure>

Now you will see the Detailed overview of Jenkins

<figure><img src="/files/SMykQoxAa0SscbDNm6wz" alt=""><figcaption></figcaption></figure>

## Step 6 — Email Integration With Jenkins and Plugin Setup <a href="#heading-step-6-email-integration-with-jenkins-and-plugin-setup" id="heading-step-6-email-integration-with-jenkins-and-plugin-setup"></a>

Install `Email Extension Plugin` in Jenkins

<figure><img src="/files/FjKPHRnq5WraW6CciQO7" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/TPeOoFg8Atfo9NV66SAn" alt=""><figcaption></figcaption></figure>

Go to your Gmail and click on your profile

Then click on Manage Your Google Account --> click on the security tab on the left side panel you will get this page(provide mail password).

<figure><img src="/files/JzNtJTJ5TQVsYPZKRvYr" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/IFgDnmLodH1ovcrtIJTa" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/vNa8Etxjg170ebMHvbgt" alt="" width="563"><figcaption></figcaption></figure>

```
dtaw cwkz hxgd xpgpOnce the plugin is installed in Jenkins, click on manage Jenkins --> configure system there under 
```

Click on Manage Jenkins--> credentials and add your mail username and generated password

<figure><img src="/files/VIoFe3WG3FrybpWnpSn9" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/WCfg0c0MLrYMIgDclNRq" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/ceOgOxmGY3SCFzqDtMT3" alt=""><figcaption></figcaption></figure>

### This is to just verify the mail configuration

Now under the Extended E-mail Notification section configure the details as shown in the below images

<figure><img src="/files/dyr4QNjxqUwwASfpeszq" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/t0bhqHaKRF3bfItWY9rQ" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/DlCfoeGSHDs7vdnnVHbK" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/GqKJf4Jp1zdKpWV5eaE4" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/eFR4Vlnv8rpMdPje482G" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/5oneupELwpjifbOEMeyY" alt=""><figcaption></figcaption></figure>

Click on Apply and save.

## **Step 7 — Install Plugins like JDK, Sonarqube Scanner, NodeJs, OWASP Dependency Check** <a href="#heading-step-7-install-plugins-like-jdk-sonarqube-scanner-nodejs-owasp-dependency-check" id="heading-step-7-install-plugins-like-jdk-sonarqube-scanner-nodejs-owasp-dependency-check"></a>

### **7A — Install Plugin** <a href="#heading-7a-install-plugin" id="heading-7a-install-plugin"></a>

Goto Manage Jenkins →Plugins → Available Plugins →

Install below plugins

1 → Eclipse Temurin Installer (Install without restart)

2 → SonarQube Scanner (Install without restart)

3 → NodeJs Plugin (Install Without restart)

<figure><img src="/files/hhTdXOW1EzoJHWY7Jent" alt=""><figcaption></figcaption></figure>

Plugins to be Install on the jenkins -

[Eclipse Temurin installer PluginVersion1.5](https://plugins.jenkins.io/adoptopenjdk)\
[NodeJS PluginVersion1.6.1](https://plugins.jenkins.io/nodejs)\
[SonarQube Scanner for JenkinsVersion2.16.1](https://plugins.jenkins.io/sonar)

### **7B — Configure Java and Nodejs in Global Tool Configuration** <a href="#heading-7b-configure-java-and-nodejs-in-global-tool-configuration" id="heading-7b-configure-java-and-nodejs-in-global-tool-configuration"></a>

Goto Manage Jenkins → Tools → Install JDK(17) and NodeJs(16)→ Click on Apply and Save

<figure><img src="/files/coFH7MEhQlAtBI6hXUeu" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/4FryAkdWlZ4D3hBbJUcC" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/0SJd7dmSzsMR2dP2STLJ" alt=""><figcaption></figcaption></figure>

Apply & Save .

## **Step 8 — Configure Sonar Server in Manage Jenkins** <a href="#heading-step-8-configure-sonar-server-in-manage-jenkins" id="heading-step-8-configure-sonar-server-in-manage-jenkins"></a>

Grab the Public IP Address of your EC2 Instance, Sonarqube works on Port 9000, so :9000. Goto your Sonarqube Server. Click on Administration → Security → Users → Click on Tokens and Update Token → Give it a name → and click on Generate Token

<figure><img src="/files/zVKQxiiab1KnSpriNTgS" alt=""><figcaption></figcaption></figure>

click on update Token

<figure><img src="/files/xA9LAB6D3M4fHeUc2V8s" alt=""><figcaption></figcaption></figure>

Create a token with a name and generate

<figure><img src="/files/ZgXqxuqLXH3SkKJVyLjf" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/DwZlvMvhRurlFc8K4pP8" alt=""><figcaption></figcaption></figure>

copy Token

Goto Jenkins Dashboard → Manage Jenkins → Credentials → Add Secret Text. It should look like this

<figure><img src="/files/QSbZeR8tLqVczpducZjM" alt=""><figcaption></figcaption></figure>

You will this page once you click on create

<figure><img src="/files/UeBuZQzoBOkn5MohOsuh" alt=""><figcaption></figcaption></figure>

Now, go to Dashboard → Manage Jenkins → System and Add like the below image.<br>

<figure><img src="/files/JoiUPp9vPkMeD0TxA7nY" alt=""><figcaption></figcaption></figure>

Click on Apply and Save

**The Configure System option** is used in Jenkins to configure different server

**Global Tool Configuration** is used to configure different tools that we install using Plugins

We will install a sonar scanner in the tools

<figure><img src="/files/Jvuvse187YbnF0KCUjVd" alt=""><figcaption></figcaption></figure>

In the SonarQube Dashboard add a quality gate also

Administration--> Configuration-->Webhooks

<figure><img src="/files/KvqFtcWGT8zxjukZJuTI" alt=""><figcaption></figcaption></figure>

Click on Create

### Let's go to our Pipeline and add the script in our Pipeline Script.

```
pipeline{
    agent any
    tools{
        jdk 'jdk17'
        nodejs 'node16'
    }
    environment {
        SCANNER_HOME=tool 'Sonar-Scanner'
    }
    stages {
        stage('clean workspace'){
            steps{
                cleanWs()
            }
        }
        stage('Checkout from Git'){
            steps{
                git branch: 'main', url: 'https://github.com/Bhushan0151/Netflix-clone.git'
            }
        }
        stage("Sonarqube Analysis "){
            steps{
                withSonarQubeEnv('sonar-server') {
                    sh ''' $SCANNER_HOME/bin/sonar-scanner -Dsonar.projectName=Netflix \
                    -Dsonar.projectKey=Netflix '''
                }
            }
        }
        stage("quality gate"){
           steps {
                script {
                    waitForQualityGate abortPipeline: false, credentialsId: 'Sonar-token' 
                }
            } 
        }
        stage('Install Dependencies') {
            steps {
                sh "npm install"
            }
        }
    }
}


```

See , How can we generate the SonarQube-Script (Already added in the Above code)

<figure><img src="/files/kfv41ikySQABBayxGcWm" alt=""><figcaption></figcaption></figure>

Click on Set-up -> Locally ->&#x20;

<figure><img src="/files/s3HViFKwVwVYYrJp6uti" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/sMqUQ5DZrkvtUE54dnUt" alt=""><figcaption></figcaption></figure>

### Click on Build now, you will see the stage view like this

<figure><img src="/files/M9wKczQIoIfIMTiDEOzN" alt=""><figcaption></figcaption></figure>

### To see the report, you can go to Sonarqube Server and go to Projects.

<figure><img src="/files/kHawgQfQgHG1g1FMvZw5" alt=""><figcaption></figcaption></figure>

You can see the report has been generated and the status shows as passed.

## **Step 9 — Install OWASP Dependency Check Plugins** <a href="#heading-step-9-install-owasp-dependency-check-plugins" id="heading-step-9-install-owasp-dependency-check-plugins"></a>

<figure><img src="/files/3OTRI7vywNSl2xXNywrw" alt=""><figcaption></figcaption></figure>

First, we configured the Plugin and next, we had to configure the Tool

Goto Dashboard → Manage Jenkins → Tools →

<figure><img src="/files/ffdozMQPL9EUDFtNMxpO" alt=""><figcaption></figcaption></figure>

Click on Apply and Save here.

### Now go configure → Pipeline and add this stage to your pipeline and build.

```
stage('OWASP FS SCAN') {
            steps {
                dependencyCheck additionalArguments: '--scan ./ --disableYarnAudit --disableNodeAudit', odcInstallation: 'DP-Check'
                dependencyCheckPublisher pattern: '**/dependency-check-report.xml'
            }
        }
        stage('TRIVY FS SCAN') {
            steps {
                sh "trivy fs . > trivyfs.txt"
            }
        }

```

<figure><img src="/files/gxYiKuUsrxKW9EfPf38Z" alt=""><figcaption></figcaption></figure>

### The stage view would look like this,

<br>

<figure><img src="/files/cTJmjECG2HocFIniyRI2" alt=""><figcaption></figcaption></figure>

You will see that in status, a graph will also be generated and Vulnerabilities.

<figure><img src="/files/ZjPve9RO0v0LuGjSN9wR" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/lNE5Amay4k1NJxO6nPO3" alt=""><figcaption></figcaption></figure>

## &#x20;<a href="#heading-step-10-docker-image-build-and-push" id="heading-step-10-docker-image-build-and-push"></a>

## **Step 10 — Docker Image Build and Push** <a href="#heading-step-10-docker-image-build-and-push" id="heading-step-10-docker-image-build-and-push"></a>

We need to install the Docker tool in our system, Goto Dashboard → Manage Plugins → Available plugins → Search for Docker and install these plugins

`Docker`

`Docker Commons`

`Docker Pipeline`

`Docker API`

`docker-build-step`

and click on install without restart

<figure><img src="/files/hERCG7Z5a6RNJUknDFAT" alt=""><figcaption></figcaption></figure>

Now, goto Dashboard → Manage Jenkins → Tools →

<figure><img src="/files/wzhlDwBwPL07u5VVquUS" alt=""><figcaption></figcaption></figure>

Add DockerHub Username and Password under Global Credentials

<figure><img src="/files/G8aVdyxk4HmP9zgpP73M" alt=""><figcaption></figcaption></figure>

### Add this stage to Pipeline Script

```
stage("Docker Build & Push"){
            steps{
                script{
                   withDockerRegistry(credentialsId: 'docker', toolName: 'docker'){   
                       sh "docker build --build-arg TMDB_V3_API_KEY=37695eddd52bd25c6f350861ace0d189-t netflix ."
                       sh "docker tag netflix bhushann11/netflix:latest "
                       sh "docker push bhushann11/netflix:latest "
                    }
                }
            }
        }
        stage("TRIVY"){
            steps{
                sh "trivy image bhushann11/netflix:latest > trivyimage.txt" 
            }
        }

```

You will see the output below, with a dependency trend.

<figure><img src="/files/4Jhd53iog4jwzG1ihJUP" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/4Zrx5IjyHc2c0TH9jP6y" alt=""><figcaption></figcaption></figure>

### When you log in to Dockerhub, you will see a new image is created

<figure><img src="/files/jkOC5wCDTujAZ4pG54EF" alt=""><figcaption></figcaption></figure>

### Now Run the container to see if the game coming up or not by adding the below stage

```
stage('Deploy to container'){
            steps{
                sh 'docker run -d --name netflix -p 8081:80 sevenajay/netflix:latest'
            }
        }

```

<figure><img src="/files/kPYrhgJsL6ZBm99L7Ecd" alt=""><figcaption></figcaption></figure>

stage view

<figure><img src="/files/lmHGEhBZP7W9N7iarxP7" alt=""><figcaption></figcaption></figure>

`<Jenkins-public-ip:8081>`

### You will get this output

<figure><img src="/files/rp3gy6tvtwr9jP7me3Od" alt=""><figcaption></figcaption></figure>

## **Step 11 — Kuberenetes Setup** <a href="#heading-step-11-kuberenetes-setup" id="heading-step-11-kuberenetes-setup"></a>

Connect your machines to Putty or Mobaxtreme

**Take-Two Ubuntu 20.04 instances one for k8s master and the other one for worker.**

<figure><img src="/files/FIK2Qf9tUyi6si4TC6Px" alt=""><figcaption></figcaption></figure>

Install Kubectl on Jenkins machine also.

```
sudo apt update -y
sudo apt install curl
curl -LO https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl
sudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl
kubectl version --client

```

<figure><img src="/files/DJbKidvkSNFe9p3DKWlj" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/y8Qh2VR0eFYY5PqQYi6f" alt=""><figcaption></figcaption></figure>

#### Part 1 ----------Master Node------------ <a href="#heading-part-1-master-node" id="heading-part-1-master-node"></a>

```
sudo hostnamectl set-hostname K8s-Master
exec bash
```

#### ----------Worker Node------------ <a href="#heading-worker-node" id="heading-worker-node"></a>

```
sudo hostnamectl set-hostname K8s-Worker
exec bash
```

#### Part 2 ------------Both Master & Node ------------ <a href="#heading-part-2-both-master-andamp-node" id="heading-part-2-both-master-andamp-node"></a>

<pre><code>sudo apt-get update 

sudo apt-get install -y docker.io
sudo usermod -aG docker ubuntu
newgrp docker
<strong>sudo chmod 777 /var/run/docker.sock
</strong>
sudo curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -

sudo tee /etc/apt/sources.list.d/kubernetes.list &#x3C;&#x3C;EOF
deb https://apt.kubernetes.io/ kubernetes-xenial main
EOF

sudo apt-get update

sudo apt-get install -y kubelet kubeadm kubectl

sudo snap install kube-apiserver

</code></pre>

#### Part 3 --------------- Master --------------- <a href="#heading-part-3-master" id="heading-part-3-master"></a>

```
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/Documentation/kube-flannel.yml

```

#### ----------Worker Node------------ <a href="#heading-worker-node-1" id="heading-worker-node-1"></a>

```
sudo kubeadm join <master-node-ip>:<master-node-port> --token <token> --discovery-token-ca-cert-hash <hash>

```

<br>

<figure><img src="/files/83bJhGoVD5U01WFhAjYx" alt="" width="558"><figcaption></figcaption></figure>

Copy the config file to Jenkins master or the local file manager and save it

<figure><img src="/files/E8aUujV9fBKjJerp4JrM" alt=""><figcaption></figcaption></figure>

copy it and save it in documents or another folder save it as secret-file.txt

Note: create a secret-file.txt in your file explorer save the config in it and use this at the kubernetes credential section.

Install Kubernetes Plugin, Once it's installed successfully

<figure><img src="/files/OxlF4OzPgMf1m1pU5hPh" alt=""><figcaption></figcaption></figure>

goto manage Jenkins --> manage credentials --> Click on Jenkins global --> add credentials

<figure><img src="/files/12JsxszUStDxgyFQYKG3" alt=""><figcaption></figcaption></figure>

### Install Node\_exporter on both master and worker <a href="#heading-install-nodeexporter-on-both-master-and-worker" id="heading-install-nodeexporter-on-both-master-and-worker"></a>

Let's add Node\_exporter on Master and Worker to monitor the metrics

First, let's create a system user for Node Exporter by running the following command:

```
sudo useradd \
    --system \
    --no-create-home \
    --shell /bin/false node_exporter

```

<figure><img src="/files/GSBV4sKjTJnNNOYaPl7N" alt=""><figcaption></figcaption></figure>

You can [**download Node Exporter**](https://prometheus.io/download/) from the same page.

Use the wget command to download the binary.

```
wget https://github.com/prometheus/node_exporter/releases/download/v1.6.1/node_exporter-1.6.1.linux-amd64.tar.gz

```

<figure><img src="/files/CANTVAin0j03VZQ54PVD" alt=""><figcaption></figcaption></figure>

Extract the node exporter from the archive.

```
tar -xvf node_exporter-1.6.1.linux-amd64.tar.gz
```

<figure><img src="/files/LHyjvQZx1nlZgHwnJCpO" alt="" width="560"><figcaption></figcaption></figure>

Move binary to the /usr/local/bin.

```
sudo mv \
  node_exporter-1.6.1.linux-amd64/node_exporter \
  /usr/local/bin/

```

<figure><img src="/files/nEsG1W9EuYfXuSkeAZDE" alt=""><figcaption></figcaption></figure>

Clean up, and delete node\_exporter archive and a folder.

```
rm -rf node_exporter*

```

<figure><img src="/files/3janvzlvdAVg2f50Z8eF" alt=""><figcaption></figcaption></figure>

Verify that you can run the binary.

```
node_exporter --version

```

Node Exporter has a lot of plugins that we can enable. If you run Node Exporter help you will get all the options.

```
node_exporter --help

```

\--collector.logind We're going to enable the login controller, just for the demo.

Next, create a similar systemd unit file.

```
sudo vim /etc/systemd/system/node_exporter.service

```

<figure><img src="/files/2IgOXZEw8OUuKpXds8At" alt=""><figcaption></figcaption></figure>

```
[Unit]
Description=Node Exporter
Wants=network-online.target
After=network-online.target

StartLimitIntervalSec=500
StartLimitBurst=5

[Service]
User=node_exporter
Group=node_exporter
Type=simple
Restart=on-failure
RestartSec=5s
ExecStart=/usr/local/bin/node_exporter \
    --collector.logind

[Install]
WantedBy=multi-user.target

```

Replace Prometheus user and group to node\_exporter, and update the ExecStart command.

To automatically start the Node Exporter after reboot, enable the service.

```
sudo systemctl enable node_exporter
sudo systemctl start node_exporter
sudo systemctl status node_exporter

```

<figure><img src="/files/RS1DfYn55OaUYqXn1ZPA" alt=""><figcaption></figcaption></figure>

If you have any issues, check logs with journalctl

```
journalctl -u node_exporter -f --no-pager

```

At this point, we have only a single target in our Prometheus. There are many different service discovery mechanisms built into Prometheus. For example, Prometheus can dynamically discover targets in AWS, GCP, and other clouds based on the labels. In the following tutorials, I'll give you a few examples of deploying Prometheus in a cloud-specific environment. For this tutorial, let's keep it simple and keep adding static targets. Also, I have a lesson on how to deploy and manage Prometheus in the Kubernetes cluster.

To create a static target, you need to add job\_name with static\_configs. Go to Prometheus server

```
sudo vim /etc/prometheus/prometheus.yml

```

<figure><img src="/files/FDgBwSHmD4BdBP814PA8" alt=""><figcaption></figcaption></figure>

**prometheus.yml**

```
  - job_name: node_export_masterk8s
    static_configs:
      - targets: ["<master-ip>:9100"]

  - job_name: node_export_workerk8s
    static_configs:
      - targets: ["<worker-ip>:9100"]

```

Since we enabled lifecycle management via API calls, we can reload the Prometheus config without restarting the service and causing downtime.

Before, restarting check if the config is valid.

```
promtool check config /etc/prometheus/prometheus.yml

```

Then, you can use a POST request to reload the config.

```
curl -X POST http://localhost:9090/-/reload

```

<figure><img src="/files/uR2hJk5ulz0labYRP9GM" alt=""><figcaption></figcaption></figure>

Check the targets section

```
http://<ip>:9090/targets

```

<figure><img src="/files/ubozcrcQ8jaOplLdTUNe" alt=""><figcaption></figcaption></figure>

final step to deploy on the Kubernetes cluster

```
stage('Deploy to kubernets'){
            steps{
                script{
                    dir('Kubernetes') {
                        withKubeConfig(caCertificate: '', clusterName: '', contextName: '', credentialsId: 'k8s', namespace: '', restrictKubeConfigAccess: false, serverUrl: '') {
                                sh 'kubectl apply -f deployment.yml'
                                sh 'kubectl apply -f service.yml'
                        }   
                    }
                }
            }
        }
        
```

<figure><img src="/files/oA4RFTqZt03RCZziVUR9" alt=""><figcaption></figcaption></figure>

How to set a path of Kubernetes&#x20;

goto pipeline syntax -> sample step -> withkube config  -> credentials is the secrete k8s.txt

-> generate the path

<figure><img src="/files/mrqfcVchltvijbdAKmum" alt=""><figcaption></figcaption></figure>

Stage View

<figure><img src="/files/TKJusDIFBujLSeXKVRto" alt=""><figcaption></figcaption></figure>

In the Kubernetes cluster(master) give this command

```
kubectl get all 
kubectl get svc #use anyone

```

<figure><img src="/files/UZJSuKZxw3KhSyldoPEW" alt=""><figcaption></figcaption></figure>

## **STEP 12:Access from a Web browser with** <a href="#heading-step-12access-from-a-web-browser-with" id="heading-step-12access-from-a-web-browser-with"></a>

Output -

<figure><img src="/files/lNa54RcbSH7glQPSicPa" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/mHkhBaEibLQVDLWVes3O" alt=""><figcaption></figcaption></figure>

Monitoring -

<figure><img src="/files/BhRTZOmQKF0dgBuu0wF1" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/fHoKzmjkrBajb02Q5Y90" alt=""><figcaption></figcaption></figure>

### **Complete Pipeline** <a href="#heading-complete-pipeline" id="heading-complete-pipeline"></a>

```
pipeline{
    agent any
    tools{
        jdk 'jdk17'
        nodejs 'node16'
    }
    environment {
        SCANNER_HOME=tool 'Sonar-Scanner'
    }
    stages {
        stage('clean workspace'){
            steps{
                cleanWs()
            }
        }
        stage('Checkout from Git'){
            steps{
                git branch: 'main', url: 'https://github.com/Bhushan0151/Netflix-clone.git'
            }
        }
        stage("Sonarqube Analysis "){
            steps{
                withSonarQubeEnv('sonar-server') {
                    sh ''' $SCANNER_HOME/bin/sonar-scanner -Dsonar.projectName=Netflix \
                    -Dsonar.projectKey=Netflix '''
                }
            }
        }
        stage("quality gate"){
           steps {
                script {
                    waitForQualityGate abortPipeline: false, credentialsId: 'Sonar-token' 
                }
            } 
        }
        stage('Install Dependencies') {
            steps {
                sh "npm install"
            }
        }
        
        stage('OWASP FS SCAN') {
            steps {
                dependencyCheck additionalArguments: '--scan ./ --disableYarnAudit --disableNodeAudit', odcInstallation: 'DP-Check'
                dependencyCheckPublisher pattern: '**/dependency-check-report.xml'
            }
        }
        stage('TRIVY FS SCAN') {
            steps {
                sh "trivy fs . > trivyfs.txt"
            }
        }
        
        stage("Docker Build & Push"){
            steps{
                script{
                   withDockerRegistry(credentialsId: 'docker', toolName: 'docker'){   
                       sh "docker build --build-arg TMDB_V3_API_KEY=37695eddd52bd25c6f350861ace0d189 -t netflix ."
                       sh "docker tag netflix bhushann11/netflix:latest "
                       sh "docker push bhushann11/netflix:latest "
                    }
                }
            }
        }
        stage("TRIVY"){
            steps{
                sh "trivy image bhushann11/netflix:latest > trivyimage.txt" 
            }
        }
        
        stage('Deploy to container'){
            steps{
                sh 'docker run -d --name netflix -p 8081:80 bhushann11/netflix:latest'
            }
        }
        
        stage('Deploy to kubernets'){
            steps{
                script{
                    dir('Kubernetes') {
                        withKubeConfig(caCertificate: '', clusterName: '', contextName: '', credentialsId: 'K8s', namespace: '', restrictKubeConfigAccess: false, serverUrl: '') {
                                sh 'kubectl apply -f deployment.yml'
                                sh 'kubectl apply -f service.yml'
                            }
                        }
                    }
                }
            }
        }
    }



```

## **Step 13: Terminate instances.** <a href="#heading-step-13-terminate-instances" id="heading-step-13-terminate-instances"></a>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://bhushans-devops-organization.gitbook.io/advanced-projects/netflix-clone-ci-cd-pipeline-or-jenkins-or-docker-or-kubernetes-or-monitoring-or-devsecops.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
