Skip to main content

Command Palette

Search for a command to run...

🚀 Jenkins Complete Guide

Published
•29 min read•View as Markdown
A

Aspiring DevOps Engineer with hands-on experience in Linux, AWS EC2, Docker, Jenkins, and CI/CD pipelines. Currently learning and undergoing training in DevOps tools with a strong focus on automation and cloud technologies. Worked on end-to-end CI/CD implementation and application deployment on AWS. Actively seeking entry-level DevOps opportunities to learn, contribute, and grow. Feel free to connect with me for DevOps opportunities, learning discussions, or collaborations.

Introduction to jenkins

❓what is jenkins ?

Jenkins is an open-source automation server used to implement Continuous Integration (CI) and Continuous Delivery/Deployment (CD) in software development. It automates the process of building, testing, and deploying applications whenever there are changes in the source code.

Jenkins works by integrating with version control systems like Git, build tools like Maven, testing frameworks, and deployment tools, allowing teams to detect issues early and deliver software faster and more reliably.

Why Jenkins is used:

  • Automates build, test, and deployment processes

  • Reduces manual work and human errors

  • Enables faster software delivery

Note 📝:

Jenkins is not just a CI tool; it is a complete automation platform widely used in DevOps for building robust CI/CD pipelines.

❓ What is CI/CD?

CI/CD stands for Continuous Integration and Continuous Delivery / Continuous Deployment.
It is a DevOps practice that automates the process of building, testing, and deploying applications whenever there is a change in the source code.

CI/CD helps teams deliver software faster, more reliably, and with fewer errors by reducing manual intervention.

🔹 1. Continuous Integration (CI)

What is CI?

Continuous Integration is the practice of frequently merging code changes into a shared repository, followed by automatic build and testing.

Why CI is used?

  • Detect bugs early

  • Avoid merge conflicts

  • Ensure code quality

  • Faster feedback to developers

Key Features of CI

  • Automatic builds

  • Automated unit tests

  • Code quality checks

  • Immediate feedback on failures

Example Tools

  • Jenkins, GitHub Actions, GitLab CI

  • Maven, Gradle

  • JUnit, TestNG

Note 📝

In CI, every code commit triggers a build and test automatically.


🔹 2. Continuous Delivery (CD)

What is Continuous Delivery?

Continuous Delivery ensures that the application is always in a deployable state after passing CI stages.
Deployment to production requires manual approval.

Why use Continuous Delivery?

  • Safe and controlled releases

  • Reduced deployment risk

  • Faster time to market

Features

  • Automated deployments to staging/QA

  • Manual approval for production

  • Release-ready artifacts

Note 📝

Continuous Delivery stops before production deployment.


🔹 3. Continuous Deployment (CD)

What is Continuous Deployment?

Continuous Deployment is an extension of Continuous Delivery where every successful build is automatically deployed to production without manual approval.

Why use Continuous Deployment?

  • Fully automated releases

  • Faster feature delivery

  • Ideal for mature DevOps teams

Features

  • Zero manual intervention

  • Fully automated pipeline

  • High confidence in automation

Note 📝

Continuous Deployment requires strong testing and monitoring.

🔁 CI vs CD (Delivery vs Deployment)

| Feature                | CI | Continuous Delivery | Continuous Deployment |
| ---------------------- | -- | ------------------- | --------------------- |
| Code Build             | ✔️ | ✔️                  | ✔️                    |
| Testing                | ✔️ | ✔️                  | ✔️                    |
| Manual Approval        | ❌ | ✔️                  | ❌                     |
| Auto Production Deploy | ❌ | ❌                  | ✔️                    |

🏗️ CI/CD Pipeline Flow

Code Commit
   ↓
Build
   ↓
Test
   ↓
Code Quality Check (SonarQube)
   ↓
Artifact Storage (Nexus)
   ↓
Deploy (Staging / Prod) (Tomcat)
  • Jenkins

  • GitHub Actions

  • GitLab CI/CD

  • Azure DevOps

  • CircleCI

🎯 Benefits of CI/CD

  • Faster software delivery

  • Early bug detection

  • Improved code quality

  • Reduced manual errors

  • Better collaboration

📝 Real-Time Note (Interview Ready)

CI focuses on integrating and testing code frequently, while CD focuses on automating the release and deployment process.

📌 Summary

  • CI = Build + Test automation

  • Continuous Delivery = Ready to release (manual approval)

  • Continuous Deployment = Fully automated release


Jenkins installation and setup :

Jenkins installation and setup involves installing Java, installing Jenkins, and performing the initial configuration through the web interface. Jenkins can be installed on Linux, Windows, macOS, or using Docker. The most common production setup is on Linux.

🔹 Step 1: Prerequisites

  • Java (JDK 11 or 17 recommended)

  • Minimum 2 GB RAM

  • Open port 8080

  • Internet access for plugins

  • Launch an Instances EC2-user and connect to the server

check java is install or not

java -version

🔹 Step 2: Jenkins Installation (RHEL )

→ LTS[Long Term Support] — -> stable version without any issues.
→ search on google [ download jenkins ] → LTS → Redhat/fedora/centos

switch to root user :

sudo su -
yum install wget tree -y

Install jenkins and java 21

sudo wget -O /etc/yum.repos.d/jenkins.repo \
    https://pkg.jenkins.io/redhat-stable/jenkins.repo
sudo rpm --import https://pkg.jenkins.io/redhat-stable/jenkins.io-2023.key
sudo yum upgrade
# Add required dependencies for the jenkins package
sudo yum install fontconfig java-21-openjdk
sudo yum install jenkins
sudo systemctl daemon-reload

🔹 Step 3: Start and Enable Jenkins Service

sudo systemctl start jenkins
sudo systemctl enable jenkins
sudo systemctl status jenkins

🔹 Step 4: Access Jenkins UI

Open browser:

http://<server-ip>:8080    #please make sure to enable 8080 port

🔹 Step 5: Unlock Jenkins

Get initial admin password:

cat /var/lib/jenkins/secrets/initialAdminPassword

🔹 Step 6: Create Admin User

  • Username

  • Password

  • Email

  • Save and continue

🔹 Step 8: Jenkins Setup Completion

  • Confirm Jenkins URL

  • Finish setup

“Jenkins installation includes installing Java, Jenkins package, unlocking Jenkins using the initial admin password, installing plugins, and configuring global tools and credentials.”

Jenkins Job types

we have multipule of job type but we will focus on :

  1. freestyle job

  2. pipeline jobs (Scripted and declrative pipeline)

  3. maven job

1.Jenkins Freestyle Job Configuration

A Freestyle Job is a basic Jenkins project that allows you to:

  • Pull code from a repository

  • Run shell commands or scripts

  • Build applications

  • Deploy artifacts

  • Trigger actions based on conditions

It’s ideal for beginners and small automation tasks.

1️⃣ Different Servers Architecture (High-Level)

Developer
   |
   |  (git push)
   v
Git Server (GitHub / GitLab)
   |
   |  (pull code)
   v
Jenkins Server
   |       |        |
   |       |        |
   |   SonarQube   Nexus
   |   Server      Server
   |
   v
Tomcat Server

Servers Used :

ServerPurpose
Git ServerSource code repository
Jenkins ServerCI/CD orchestration
SonarQube ServerCode quality analysis
Nexus ServerArtifact repository
Tomcat ServerApplication deployment

3️⃣ Prerequisites (On Each Server)

🔹 Jenkins Server

  • Java installed

  • Jenkins installed

  • Plugins:

    • Git Plugin

    • Maven Integration Plugin

    • SonarQube Scanner

    • Nexus Artifact Uploader

    • Deploy to Container (Tomcat)

🔹 Maven Server

  • Java

  • Maven installed

🔹 SonarQube Server

  • Java

  • SonarQube running

  • Generate Sonar Token

🔹 Nexus Server

  • Nexus running

  • Maven Hosted Repository created

  • Credentials ready

🔹 Tomcat Server

  • Tomcat installed & running

  • Manager App enabled

  • Username/password configured

4️⃣ Step-by-Step Jenkins Freestyle Job Configuration

🔹 Step 1: Create Jenkins Freestyle Job

Jenkins Dashboard → New Item → Freestyle Project Name: end-to-end-freestyle-project

🔹Step 2 :Configure Git (Source Code)

Source Code Management → Git Repository URL: https://github.com/user/repo.git Credentials: Git credentials Branch: main / master/dev

🔹Step 3 : Configure Build (Maven)

🔹 Add Maven Build Step

Build → Invoke Top-Level Maven Targets Maven Version: Maven-3 —> Goals:

clean package

Step 4 :Integrate SonarQube

🔹 Add Build Step Maven Goal:

sonar:sonar

✔ Code gets analyzed
✔ Quality Gate checked

Step 5 :Upload Artifact to Nexus

🔹 Add Post-Build Action

Post-build Actions → Nexus Artifact Uploader

Fill:

  • Group ID

  • Artifact ID

  • Version

  • Packaging: war

  • Repository: maven-releases / snapshots

  • Nexus URL

  • Credentials

✔ WAR file stored in Nexus

🔹 Step 6: Deploy to Tomcat Server

  1. Post-Build Actions → Add

  2. Select Deploy war/ear to a container

  3. Configure:

    • WAR file path:

        **/*.war
      
    • Container: Tomcat

    • Tomcat URL

    • Credentials

✅ Application deployed automatically to Tomcat.

🔁 End-to-End Flow

  1. Developer pushes code to Git

  2. Jenkins pulls code

  3. Maven builds project

  4. SonarQube analyzes code

  5. WAR uploaded to Nexus

  6. WAR deployed to Tomcat

  7. Application live 🎉

Real-Time Interview Line (Very Important)

“In our architecture, Jenkins acts as the CI/CD orchestrator.
It pulls code from Git, builds using Maven, performs static code analysis using SonarQube, stores artifacts in Nexus, and finally deploys the WAR file to Tomcat hosted on a separate server.”

Jenkins Maven Job Configuration

Step-by-Step Jenkins Maven Job Configuration

STEP 1️⃣ Install Required Tools in Jenkins

STEP 2️⃣ Configure SonarQube in Jenkins

STEP 3️⃣ Configure Nexus Credentials

STEP 4️⃣ Configure Tomcat Credentials

STEP 5️⃣ Create Jenkins Maven Job

Jenkins Dashboard → New iteam → Name the job ( ex.,Maven job ) →select maven project →done

STEP 6️⃣ Git Configuration

Source Code Management

  • Git

  • Repository URL

  • Credentials (if private)

  • Branch: main / master

STEP 7️⃣ Maven Build Configuration

Build Root POM

Goals and options

clean package

👉 This:

  • Downloads dependencies

  • Builds .war file

STEP 8️⃣ SonarQube Code Analysis

Maven goals:

sonar:sonar

✔ Code quality check
✔ Fails build if quality gate fails (optional)

STEP 9️⃣ Upload Artifact to Nexus

Option 1: Using pom.xml

Add:

<distributionManagement>
  <repository>
    <id>nexus</id>
    <url>http://<nexus-ip>:8081/repository/maven-releases/</url>
  </repository>
</distributionManagement>

Then run:

mvn deploy

STEP 🔟 Deploy WAR to Tomcat

Post-build Action → Deploy to Container

  • Container: Tomcat

  • Credentials: tomcat-creds

  • WAR file:

**/*.war
  • Context path:
/myapp

4️⃣ End-to-End Flow (Execution Order)

  1. Developer pushes code to Git

  2. Jenkins pulls code

  3. Maven builds project

  4. SonarQube analyzes code

  5. Artifact uploaded to Nexus

  6. WAR deployed to Tomcat

  7. Application is live 🎉

5️⃣ Real-Time Interview One-Liner (Very Important)

“Jenkins pulls code from Git, builds it using Maven, performs static code analysis with SonarQube, stores artifacts in Nexus, and deploys the WAR file to Tomcat running on a separate server.”

🔹 Jenkins Freestyle Job vs Maven Job

FeatureFreestyle JobMaven Job
Job TypeGeneric jobSpecialized for Maven projects
Build Tool SupportAny tool (Shell, Ant, Maven, Gradle, etc.)Only Maven
Configuration StyleManual step-by-step configurationMaven-centric configuration
Build CommandUser defines commands (e.g., mvn clean install)Jenkins manages Maven lifecycle automatically
POM HandlingJenkins does not read pom.xml automaticallyJenkins reads pom.xml
Dependency ManagementManualAutomatic via Maven
ReportingManual setup for reportsBuilt-in Maven reports
FlexibilityVery highLimited to Maven projects
Pipeline ComplexityBest for simple or custom workflowsBest for pure Java/Maven projects
Use CaseAny project typeJava projects using Maven

🔹 Freestyle Job (Simple Explanation)

  • Most basic and flexible Jenkins job

  • You define each step manually

  • Supports any language or tool

  • Common steps:

    • Git checkout

    • Shell execution

    • Maven build

    • Tomcat deploy

🔹 Maven Job (Simple Explanation)

  • Designed only for Maven projects

  • Jenkins understands pom.xml

  • Automatically handles:

    • Dependencies

    • Build lifecycle

    • Test results


🔹 Types of Jenkins Pipeline

1️⃣ Declarative Pipeline

2️⃣ Scripted Pipeline

1️⃣ Declarative Pipeline

A Declarative Pipeline is a modern, structured way to define Jenkins pipelines using a predefined, easy-to-read syntax. It is designed to simplify pipeline creation, enforce best practices, and make CI/CD pipelines more maintainable and readable.

🔹 Interview One-Liner

Declarative Pipeline is a structured, code-based way to define Jenkins pipelines with readable syntax, making CI/CD automation easier and maintainable.

Example : 🔹 Declarative Pipeline: Git + Maven + SonarQube + Nexus + Tomcat

📌 Prerequisites (Important)

  • Jenkins configured with:

    • Maven

    • SonarQube Server

    • Nexus Repository

    • Tomcat Server

  • Required Jenkins plugins:

    • Git

    • Maven Integration

    • SonarQube Scanner

    • Deploy to Container (Tomcat)

  • Credentials configured in Jenkins:

    • Git credentials

    • SonarQube token

    • Nexus credentials

    • Tomcat credentials

Decleractive pipeline Example :

pipeline {
    agent any

    tools {
        maven 'MAVEN3'
    }

    environment {
        SONARQUBE_SERVER = 'SonarQube-Server'
        NEXUS_REPO = 'nexus-releases'
        NEXUS_URL = 'http://nexus:8081'
        TOMCAT_URL = 'http://tomcat:8080'
    }

    stages {

        stage('Checkout Code') {
            steps {
                git branch: 'main',
                    credentialsId: 'git-creds',
                    url: 'https://github.com/example/maven-web-app.git'
            }
        }

        stage('Build with Maven') {
            steps {
                sh 'mvn clean package'
            }
        }

        stage('SonarQube Analysis') {
            steps {
                withSonarQubeEnv("${SONARQUBE_SERVER}") {
                    sh '''
                      mvn sonar:sonar \
                      -Dsonar.projectKey=maven-web-app \
                      -Dsonar.projectName=maven-web-app
                    '''
                }
            }
        }

        stage('Quality Gate') {
            steps {
                timeout(time: 5, unit: 'MINUTES') {
                    waitForQualityGate abortPipeline: true
                }
            }
        }

        stage('Upload Artifact to Nexus') {
            steps {
                sh 'mvn deploy'
            }
        }

        stage('Deploy to Tomcat') {
            steps {
                deploy adapters: [
                    tomcat9(
                        credentialsId: 'tomcat-creds',
                        path: '',
                        url: "${TOMCAT_URL}"
                    )
                ],
                contextPath: 'myapp',
                war: 'target/*.war'
            }
        }
    }

    post {
        success {
            echo "✅ CI/CD Pipeline executed successfully!"
        }
        failure {
            echo "❌ Pipeline failed. Please check logs."
        }
    }
}

🔹 Pipeline Flow (Easy Explanation)

1️⃣ Git – Pulls source code from GitHub
2️⃣ Maven Build – Compiles & packages WAR
3️⃣ SonarQube – Code quality & security analysis
4️⃣ Quality Gate – Stops pipeline if quality fails
5️⃣ Nexus – Stores WAR artifact
6️⃣ Tomcat – Deploys application

🔹 Key Sections

SectionDescription
pipelineRoot block for the pipeline
agentDefines where the pipeline runs
stagesContains all the stages of the pipeline
stageRepresents a step like Build, Test, Deploy
stepsActual commands to execute in each stage
postActions to perform after pipeline execution (success/failure)

2️⃣ Scripted Pipeline

A Scripted Pipeline is the traditional, Groovy-based way of writing Jenkins pipelines. It is more flexible and powerful than Declarative Pipeline but requires programming knowledge. It gives you full control over the flow of the pipeline.

🔹 Jenkins Scripted Pipeline: Step by SteBefore creating a scripted pipeline, make sure you have:

  1. Jenkins installed and running

  2. Git plugin installed

  3. Maven installed on Jenkins

  4. SonarQube configured (if needed)

  5. Nexus repository configured (if needed)

  6. Tomcat server configured (if deployment is required)

  7. Credentials added in Jenkins for Git, Nexus, SonarQube, and Tomcat

Step 2: Create a New Pipeline Job

  1. Open Jenkins → Click “New Item”

  2. Enter a name for the job (e.g., scripted-pipeline-project)

  3. Select Pipeline → Click OK

Step 3: Configure Pipeline Script

  1. Scroll to Pipeline section

  2. Select Pipeline script (you can also use Pipeline script from SCM if storing Jenkinsfile in Git)

  3. Write your Scripted Pipeline using Groovy

Step 4: Add Stages

Add stages for each CI/CD step.

Example Stages:

  1. Checkout Code

  2. Build

  3. Test

  4. SonarQube Analysis

  5. Upload Artifact to Nexus

  6. Deploy to Tomcat

node {
    stage('Checkout') {
        git branch: 'main', url: 'https://github.com/example/repo.git', credentialsId: 'git-creds'
    }

    stage('Build') {
        sh 'mvn clean package'
    }

    stage('Test') {
        sh 'mvn test'
    }
}

Step 6: Add SonarQube Analysis (Optional)

stage('SonarQube Analysis') {
    withSonarQubeEnv('SonarQube-Server') {
        sh 'mvn sonar:sonar -Dsonar.projectKey=myproject'
    }
}

Quality Gate Check:

stage('Quality Gate') {
    timeout(time: 5, unit: 'MINUTES') {
        def qg = waitForQualityGate()
        if (qg.status != 'OK') {
            error "Pipeline aborted due to quality gate failure: ${qg.status}"
        }
    }
}

Step 7: Upload Artifact to Nexus (Optional)

stage('Upload to Nexus') {
    sh 'mvn deploy'
}

Step 8: Deploy to Tomcat (Optional)

stage('Deploy to Tomcat') {
    deploy adapters: [tomcat9(credentialsId: 'tomcat-creds', url: 'http://tomcat:8080')],
           contextPath: 'myapp',
           war: 'target/*.war'
}

Step 9: Error Handling

Wrap the entire pipeline in try/catch/finally to handle errors:

node {
    try {
        stage('Build') {
            sh 'mvn clean package'
        }
    } catch (err) {
        echo "Pipeline failed: ${err}"
        currentBuild.result = 'FAILURE'
    } finally {
        echo "Pipeline execution completed."
    }
}

Step 10: Save and Run

  1. Click Save

  2. Click Build Now

  3. Monitor Console Output for logs

Code

node {  // Run on any available Jenkins node

    // Define environment variables
    def SONARQUBE_SERVER = 'SonarQube-Server'
    def NEXUS_URL = 'http://nexus:8081'
    def TOMCAT_URL = 'http://tomcat:8080'

    try {
        // Stage 1: Checkout code from Git
        stage('Checkout Code') {
            git branch: 'main',
                credentialsId: 'git-creds',
                url: 'https://github.com/example/maven-web-app.git'
            echo "✅ Code checked out successfully!"
        }

        // Stage 2: Maven Build
        stage('Build with Maven') {
            sh 'mvn clean package'
            echo "✅ Build completed successfully!"
        }

        // Stage 3: SonarQube Analysis
        stage('SonarQube Analysis') {
            withSonarQubeEnv(SONARQUBE_SERVER) {
                sh '''
                  mvn sonar:sonar \
                  -Dsonar.projectKey=maven-web-app \
                  -Dsonar.projectName=maven-web-app
                '''
            }
            echo "✅ SonarQube analysis completed!"
        }

        // Stage 4: Quality Gate
        stage('Quality Gate') {
            timeout(time: 5, unit: 'MINUTES') {
                def qg = waitForQualityGate()
                if (qg.status != 'OK') {
                    error "❌ Pipeline aborted: Quality Gate failed (${qg.status})"
                }
            }
            echo "✅ Quality Gate passed!"
        }

        // Stage 5: Upload Artifact to Nexus
        stage('Upload to Nexus') {
            sh 'mvn deploy'
            echo "✅ Artifact uploaded to Nexus!"
        }

        // Stage 6: Deploy to Tomcat
        stage('Deploy to Tomcat') {
            deploy adapters: [
                tomcat9(
                    credentialsId: 'tomcat-creds',
                    path: '',
                    url: "${TOMCAT_URL}"
                )
            ],
            contextPath: 'myapp',
            war: 'target/*.war'
            echo "✅ Deployed to Tomcat successfully!"
        }

    } catch (err) {
        echo "❌ Pipeline failed: ${err}"
        currentBuild.result = 'FAILURE'
    } finally {
        echo "Pipeline execution completed."
    }
}

✅ Features in this Pipeline

  1. Git Checkout – Pulls code from GitHub

  2. Maven Build – Compiles and packages the project

  3. SonarQube Analysis – Static code analysis

  4. Quality Gate – Pipeline fails if code quality is poor

  5. Nexus Deployment – Uploads artifact to Nexus repository

  6. Tomcat Deployment – Deploys WAR file to Tomcat

  7. Error Handling – Catches errors and marks build as failed

🔹 Key Points for Scripted Pipeline

  • Uses Groovy scripting (node {} block)

  • Highly flexible and allows loops, conditions, and custom logic

  • Best for complex CI/CD workflows

  • Error handling via try/catch/finally.

🔹 Key Differences of Declerative and Scripted Pipelines

FeatureDeclarative PipelineScripted Pipeline
Syntaxpipeline {} structurednode {} Groovy code
ReadabilityHigh, easy for beginnersMedium, code-heavy
Error Handlingpost {} blocktry/catch/finally
FlexibilityLimitedVery high, full Groovy control
Use CaseStandard CI/CD flowsComplex, dynamic workflows
Learning CurveEasyAdvanced

🔹 Quick Takeaway

  • Declarative → Best for most CI/CD pipelines, clean and readable

  • Scripted → Use when pipeline needs dynamic stages or advanced logic


Multibranch Pipeline in Jenkins

A Multibranch Pipeline is a Jenkins job that automatically discovers, creates, and runs pipelines for every branch in a Git repository.

In simple words:

“Jenkins automatically builds each Git branch using its own Jenkinsfile.”

🔹 Why Multibranch Pipeline is Used?

  • 🔀 Handles multiple branches (main, dev, feature, release)

  • 📄 Each branch can have its own Jenkinsfile

  • 🔄 Automatic build on branch creation or code push

  • 🚀 Perfect for Git-based CI/CD workflows

🔹 Simple Example

Git Repository:

main        → Jenkinsfile
dev         → Jenkinsfile
feature-1  → Jenkinsfile

Jenkins:

Job-main
Job-dev
Job-feature-1

All created automatically ✨

🔹 How Multibranch Pipeline Works (Flow)

Git Repository
     ↓
Jenkins scans branches
     ↓
Finds Jenkinsfile
     ↓
Creates pipeline per branch
     ↓
Builds automatically

🔹 Step-by-Step Configuration

✅ Step 1: Create Multibranch Pipeline Job

  1. Go to Jenkins Dashboard

  2. Click New Item

  3. Enter job name (e.g., my-multibranch-pipeline)

  4. Select Multibranch Pipeline

  5. Click OK

✅ Step 2: Configure Branch Source (Git)

  1. Under Branch Sources

  2. Select Git

  3. Enter:

    • Repository URL

    • Credentials (if private repo)

✅ Step 3: Configure Build Triggers

Under Build Configuration:

  • Script Path: Jenkinsfile (default)

Under Scan Multibranch Pipeline Triggers:

  • ✅ Periodically if not otherwise run
    Example:

      H/5 * * * *
    

    (Scan every 5 minutes)

OR

  • Use GitHub Webhook for instant builds ⚡

✅ Step 4: Save the Job

  • Jenkins will scan the repository

  • Automatically detect all branches with a Jenkinsfile

  • Create separate pipelines for each branch

🔹 Sample Jenkinsfile (Used in Each Branch)

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo "Building branch: ${env.BRANCH_NAME}"
                sh 'mvn clean package'
            }
        }
    }
}

🔹 Key Environment Variables in Multibranch

VariableMeaning
BRANCH_NAMECurrent Git branch
CHANGE_IDPull request ID
CHANGE_BRANCHSource branch of PR
CHANGE_TARGETTarget branch

🔹 Interview One-Liner ⭐

Multibranch Pipeline automatically creates and manages Jenkins pipelines for every Git branch using Jenkinsfile.


🔹 What are Build Triggers?

Build Triggers in Jenkins are mechanisms that automatically start a job when certain conditions are met, without manual intervention. They are essential for continuous integration (CI) and continuous delivery (CD).

🔹 Types of Build Triggers in Jenkins

1️⃣ Build Periodically

  • Runs the job on a scheduled time using CRON syntax.

  • Example: run every night at 2 AM.

H 2 * * *
  • H → Hash to spread load across nodes

  • 2 → 2 AM

✅ Use case: Nightly builds, reports, or backups

2️⃣ Poll SCM (Source Code Management)

  • Jenkins checks the Git/SCM repository at regular intervals.

  • If changes are detected, the build is triggered automatically.

Example CRON:

H/15 * * * *
  • Checks every 15 minutes

✅ Use case: Trigger build when developers push code

3️⃣ GitHub / Bitbucket Webhook Trigger

  • Uses webhooks to trigger builds immediately after a push to a repository.

  • Faster than polling SCM.

  • Requires:

    • Webhook setup in GitHub/Bitbucket

    • “GitHub hook trigger for GITScm polling” enabled in Jenkins

✅ Use case: CI/CD for code pushed to GitHub

4️⃣ Build after other projects

  • Trigger this job after another Jenkins job completes.

  • Useful for multi-stage pipelines across jobs.

✅ Use case: Deploy job triggers after build job succeeds

5️⃣ Trigger builds remotely (e.g., via script or URL)

  • Jenkins exposes a special URL with an authentication token.

  • Can trigger a build from:

    • Scripts

    • Curl commands

    • External tools

Example URL:

http://<jenkins-server>/job/<job-name>/build?token=<token>

✅ Use case: Trigger Jenkins from external systems like Jira, Docker, or cron jobs

6️⃣ Build periodically with parameters

  • Similar to “Build Periodically” but allows parameterized builds at scheduled times.

  • Useful for dynamic builds with different configurations.

7️⃣ Pipeline Triggers (for declarative/pipeline jobs)

  • triggers {} block in Declarative Pipeline allows automated triggering.

Example:

pipeline {
    triggers {
        pollSCM('H/15 * * * *')
    }
    stages {
        stage('Build') {
            steps {
                sh 'mvn clean package'
            }
        }
    }
}

✅ Use case: Automate pipeline runs without manual intervention

🔹 Summary Table

TriggerWhat it doesSimple Example
Poll SCMJenkins checks your source code (Git, SVN) at intervals“Check Git every 5 minutes, if new code → build”
Build periodicallyRuns job at scheduled time (like cron)“Build every day at 10 AM”
GitHub hook / WebhookJenkins listens for changes from GitHub“When someone pushes code → build automatically”
Upstream/Downstream projectsTrigger job when another job finishes“Job B runs after Job A succeeds”
Remote triggerTrigger job using a URL“Other apps/scripts can start this job via HTTP call”

🔹 Interview One-Liner

Build Triggers in Jenkins automatically start jobs based on schedule, SCM changes, other jobs, or external requests, enabling continuous integration and delivery.


JaCoCo - code Coverage Tool

JaCoCo (Java Code Coverage) is a free, open-source tool used to measure how much of your Java code is tested by unit tests.

In simple words:

“It tells you which lines of your code are tested and which are not.”

Goal: Ensure code coverage is at least 80%.

1)Identify untested code using JaCoCo reports.

2)Write more tests for uncovered areas.

NOTE:Set Jenkins to fail builds if coverage is below 80%

Safe Restart vs Normal Restart in Jenkins

FeatureNormal RestartSafe Restart
Running JobsStopped immediatelyAllowed to finish
New JobsStoppedNot started
RiskHigh (job failure)Low
Best ForEmergency restartPlanned restart

🔹 Interview One-Liner ⭐

Normal restart stops Jenkins immediately, while safe restart waits for all running jobs to complete before restarting.


Next Build Number Plugin

--> After insatlling this plugin we can give our own build number, The next number must be greater than the previous build number only.

NOTE: in linux server /var/lib/jenkins/jobs/jio-dev/jobs/nextBuildNumber

file is available , But some time times we dont have an access to linux server to use this


Jenkins Audit Trail Plugin?

The Audit Trail Plugin in Jenkins is used to track and record user activities in Jenkins.

In simple words:

“It keeps a log of who did what and when in Jenkins.”

🔹 What Activities Does It Track?

The plugin records:

  • 👤 User logins & logouts

  • 🛠️ Job creation, deletion, and configuration changes

  • 🔐 Credential changes

  • ⚙️ System configuration changes

  • ▶️ Job start / stop actions

🔹 Why Is It Important?

  • Security & compliance

  • Troubleshooting

  • Accountability

  • Audit requirements (ISO, SOC, etc.)

🔹 Where Are Logs Stored? Usually in a log file on the Jenkins server

Example path:

bash Copy code /var/log/jenkins/audit.log (Path can be customized)Step 1: Install Plugin
  1. Go to Manage Jenkins → Manage Plugins

  2. Search for Audit Trail

  3. Install and restart Jenkins

Step 2: Configure Plugin

  1. Go to Manage Jenkins → Configure System

  2. Scroll to Audit Trail

  3. Configure:

    • Log file location

    • Log format

    • Include / exclude events

    • Enable logging

🔹 Sample Audit Log Entry

2025-01-05 10:32:12 user=akhila action=JOB_CONFIG_CHANGED job=my-pipeline

This means:

  • User akhila

  • Modified job configuration

  • Job name my-pipeline

🔹 Interview One-Liner ⭐

Jenkins Audit Trail Plugin logs all user and system activities, helping track changes for security and compliance purposes.


Build Number in Jenkins

A build number is the automatic number Jenkins gives to every build of a job.

Example:

Build #1 → #2 → #3 → #4 …

🔹 Can We Change Build Numbers?

✅ You cannot directly edit a build number,
but
✅ you can reset or start build numbers from a new value.

🔹 Method 1: Change Build Number Using Jenkins UI (Easiest)

  1. Open your Jenkins Job

  2. Click Configure

  3. Check “This project is parameterized”

  4. Add String Parameter

    • Name: BUILD_NUMBER

    • Default Value: 100

  5. Use it in your build:

echo "Build Number is $BUILD_NUMBER"

📌 This does not change Jenkins internal build number,
but lets you control versioning.

🔹 Method 2: Reset Jenkins Build Number (Real Change)

⚠️ Use carefully

  1. Go to Jenkins job directory:
cd /var/lib/jenkins/jobs/<job-name>/
  1. Open nextBuildNumber file:
cat nextBuildNumber
  1. Edit the number:
echo 50 > nextBuildNumber
  1. Save and run the job
    ➡ Next build will start from #50

🔹 Method 3: Delete Old Builds

  1. Open Jenkins job

  2. Delete old builds (#1, #2, #3…)

  3. Jenkins will continue from the next number

📌 This doesn’t reset but cleans history.

🔹 Interview One-Liner ⭐

Jenkins build numbers cannot be edited, but they can be reset by updating the nextBuildNumber file or managed using parameters.


Build Name and Description Setter Plugin

The Build Name and Description Setter Plugin is used to change the build name and build description automatically during a Jenkins build.

In simple words:

“It helps you give meaningful names and descriptions to Jenkins builds instead of just build numbers.”

🔹 Why Do We Need It?

By default, Jenkins shows builds like:

#15
#16
#17

After using this plugin, builds can look like:

Release-1.2.0
Feature-login-#45
Build-2025-01-10

✅ Makes builds easy to identify
✅ Helps in debugging & tracking
✅ Useful for release pipelines

🔹 How to Configure (Step by Step)

Step 1: Install Plugin

  1. Go to Manage Jenkins → Manage Plugins

  2. Search Build Name and Description Setter

  3. Install and restart Jenkins

Step 2: Configure in Job

For Freestyle Job:

  1. Open Job → Configure

  2. Under Build Environment

  3. Check “Set Build Name”

  4. Enter build name:

Release-${BUILD_NUMBER}
  1. (Optional) Set description:
Branch: ${GIT_BRANCH}
Commit: ${GIT_COMMIT}

For Pipeline Job:

stage('Set Build Name') {
    steps {
        buildName "Release-${BUILD_NUMBER}"
        buildDescription "Branch: ${env.GIT_BRANCH}"
    }
}

🔹 Interview One-Liner ⭐

The Build Name and Description Setter Plugin is used to assign meaningful names and descriptions to Jenkins builds for better visibility and tracking.


Role-Based Access Control (RBAC)

Role-Based Access Control means giving permissions to users based on roles, not individually.

In simple words:

“Users get access based on their role, like Admin, Developer, Tester.”

🔹 Step-by-Step Configuration

✅ Step 1: Install RBAC Plugin

  1. Go to Manage Jenkins → Manage Plugins

  2. Search for Role-based Authorization Strategy

  3. Install and restart Jenkins

✅ Step 2: Enable Role-Based Authorization

  1. Go to Manage Jenkins → Configure Global Security

  2. Under Authorization

  3. Select Role-Based Strategy

  4. Save

✅ Step 3: Manage Roles

  1. Go to Manage Jenkins → Manage and Assign Roles

  2. You’ll see:

    • Manage Roles

    • Assign Roles

✅ Step 4: Create Roles

🔹 Global Roles

Controls overall Jenkins access

Example:

  • admin

    • Overall → Administer
  • developer

    • Overall → Read

    • Job → Build, Read

  • viewer

    • Overall → Read only

🔹 Project Roles

Controls access to specific jobs using patterns

Example:

  • dev-jobs

    • Job → Build, Read

    • Pattern → dev-.*

✅ Step 5: Assign Roles to Users

  1. Go to Assign Roles

  2. Enter username

  3. Check required roles

  4. Save

🔹 Role Types in Jenkins RBAC

Role TypePurpose
Global RolesJenkins-wide permissions
Project RolesJob-specific permissions
Agent RolesNode/agent access

🔹 Real-Time Example

UserRoleAccess
akhilaAdminFull Jenkins access
dev1DeveloperBuild & view jobs
qa1TesterView only

🔹 Interview One-Liner ⭐

Role-Based Access Control in Jenkins assigns permissions to users based on roles, improving security and manageability.


Slack Notification in Jenkins

Slack Notification allows Jenkins to send build status messages (SUCCESS / FAILURE / UNSTABLE) to a Slack channel automatically.

In simple words:

“Jenkins tells the team on Slack whenever a build starts, succeeds, or fails.”

🔹 What Can Jenkins Send to Slack?

  • Build success / failure

  • Job name & build number

  • Commit details

  • Who triggered the build

  • Build URL

🔹 Step-by-Step Slack Configuration in Jenkins

✅ Step 1: Create Slack App (One Time)

  1. Go to Slack → Create App

  2. Choose From scratch

  3. App name: jenkins

  4. Select your workspace

✅ Step 2: Enable Incoming Webhooks

  1. Open your Slack App

  2. Go to Incoming Webhooks

  3. Enable Activate Incoming Webhooks

  4. Click Add New Webhook to Workspace

  5. Select Slack channel (e.g., #jenkins-builds)

  6. Copy the Webhook URL

✅ Step 3: Install Slack Plugin in Jenkins

  1. Go to Manage Jenkins → Manage Plugins

  2. Search for Slack Notification Plugin

  3. Install and restart Jenkins

✅ Step 4: Configure Slack in Jenkins (Global)

  1. Go to Manage Jenkins → Configure System

  2. Scroll to Slack

  3. Fill details:

    • Workspace: your-workspace-name

    • Default Channel: #jenkins-builds

    • Credentials:

      • Add Secret Text

      • Paste Slack Webhook URL

  4. Click Test Connection

  5. Save

🔹 Step 5: Enable Slack Notification in Job

🔹 For Freestyle Job

  1. Open Job → Configure

  2. Go to Post-build Actions

  3. Select Slack Notifications

  4. Choose when to notify:

    • ✔️ Success

    • ✔️ Failure

    • ✔️ Unstable

  5. Save

post {
    success {
        slackSend channel: '#jenkins-builds',
                  message: "✅ Build SUCCESS: ${env.JOB_NAME} #${env.BUILD_NUMBER}"
    }
    failure {
        slackSend channel: '#jenkins-builds',
                  message: "❌ Build FAILED: ${env.JOB_NAME} #${env.BUILD_NUMBER}"
    }
}

🔹 Simple Flow Diagram (Text)

Code Push
   ↓
Jenkins Build
   ↓
Slack Plugin
   ↓
Slack Channel Notification

🔹 Interview One-Liner ⭐

Slack Notification in Jenkins sends automated build status updates to Slack channels for faster team communication.


🔹 Jenkins Backup

Why Jenkins Backup is Important?

Jenkins stores jobs, configurations, credentials, plugins, and build history.
If Jenkins crashes or the server fails, backup is the only way to restore everything.

  1. Manual Jenkins Backup

  2. using Thin Backup plugin

1️⃣ Jenkins Backup – Manual Method

📌 What to Backup?

Main Jenkins data is stored in JENKINS_HOME:

Common paths:

/var/lib/jenkins

Important folders/files:

  • jobs/ → All jobs & pipelines

  • config.xml → Global Jenkins configuration

  • credentials.xml → Credentials

  • plugins/ → Installed plugins

  • users/ → User data

  • secrets/ → Encryption keys

📌 Manual Backup Steps

sudo systemctl stop jenkins

Step 2: Take Backup

tar -czvf jenkins_backup_$(date +%F).tar.gz /var/lib/jenkins

Step 3: Start Jenkins

sudo systemctl start jenkins

📌 Restore Jenkins (Manual)

sudo systemctl stop jenkins
tar -xzvf jenkins_backup.tar.gz -C /
sudo systemctl start jenkins

✅ Advantages

  • Simple & reliable

  • No plugin dependency

  • Best for full system backup

❌ Disadvantages

  • Manual effort

  • No scheduling unless cron is used

  • Needs Jenkins downtime (recommended)


2️⃣ Jenkins Backup – Using ThinBackup Plugin

📌 What is ThinBackup?

ThinBackup Plugin automates Jenkins backup without stopping Jenkins.

It backs up:

  • Jobs

  • Global config

  • Plugins list

  • User data

📌 ThinBackup Configuration (Step by Step)

Step 1: Install Plugin

  1. Go to Manage Jenkins → Manage Plugins

  2. Search ThinBackup

  3. Install & restart Jenkins

Step 2: Configure ThinBackup

  1. Go to Manage Jenkins → ThinBackup

  2. Click Settings

  3. Configure:

    • Backup Directory (e.g. /backup/jenkins)

    • Backup of:

      • Jobs ✔️

      • Plugins ✔️

      • Global config ✔️

      • Users ✔️

  4. Save

Step 3: Take Backup

  • Click Backup Now

  • Jenkins will create backup automatically

Step 4: Schedule Backup

  • Enable Periodic Backup

  • Example (daily at 2 AM):

H 2 * * *

📌 Restore Using ThinBackup

  1. Go to Manage Jenkins → ThinBackup

  2. Click Restore

  3. Select backup folder

  4. Restart Jenkins

✅ Advantages

  • Automated & scheduled backups

  • No Jenkins downtime

  • Easy restore

❌ Disadvantages

  • Needs plugin

  • Not full filesystem backup

  • Secrets handled carefully

🔹 Manual vs ThinBackup Comparison

FeatureManual BackupThinBackup Plugin
Automation❌✅
Scheduling❌✅
Jenkins DowntimeRecommendedNot required
Ease of RestoreMediumEasy
Production FriendlyMediumHigh

🔹 Best Practice (Real-Time)

✔️ Use ThinBackup for daily backups
✔️ Use Manual backup weekly/monthly
✔️ Store backups in external storage (S3/NFS)
✔️ Test restore regularly

🔹 Interview One-Liner ⭐

Jenkins backup can be done manually by backing up JENKINS_HOME or automatically using the ThinBackup plugin for scheduled, non-disruptive backups.


🔹Upstream & Downstream Triggers

They are used to connect multiple Jenkins jobs, so that one job automatically triggers another job.

In simple words:

“When one job finishes, it can automatically start another job.”


🔹 What is Parallel Job Execution in Jenkins?

Parallel execution means running multiple jobs or stages at the same time instead of one after another.

👉 This reduces total build time and speeds up CI/CD pipelines.


🔚 Conclusion

Jenkins plays a crucial role in modern DevOps and CI/CD practices by automating the entire software delivery process. From simple Freestyle jobs to advanced Declarative and Scripted Pipelines, Jenkins provides flexibility to design workflows that fit any project size or complexity.

Throughout this blog, we explored key Jenkins concepts such as pipelines, build triggers, parallel execution, role-based access control, notifications, backups, integrations with tools like Git, Maven, SonarQube, Nexus, Tomcat, and monitoring through plugins. These features help teams achieve faster builds, better code quality, improved security, and reliable deployments.

By implementing best practices like pipeline as code, proper access control, automated backups, and notifications, Jenkins becomes not just a build tool, but a complete CI/CD automation platform.

In short, mastering Jenkins is a strong foundation for any DevOps engineer, enabling faster releases, reduced manual effort, and continuous improvement in software delivery.

🚀 With Jenkins, automation is not an option — it’s a necessity.