0% found this document useful (0 votes)
4 views33 pages

Jenkins Complete Learning Guide

The document is a comprehensive guide on Jenkins, covering installation, configuration, and usage of Jenkins for CI/CD pipelines. It includes detailed chapters on core concepts, pipeline creation, and best practices, along with hands-on exercises and interview preparation. The guide is tailored for individuals preparing for a Cloud & DevOps Engineer role, providing essential knowledge and practical skills in Jenkins.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views33 pages

Jenkins Complete Learning Guide

The document is a comprehensive guide on Jenkins, covering installation, configuration, and usage of Jenkins for CI/CD pipelines. It includes detailed chapters on core concepts, pipeline creation, and best practices, along with hands-on exercises and interview preparation. The guide is tailored for individuals preparing for a Cloud & DevOps Engineer role, providing essential knowledge and practical skills in Jenkins.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Jenkins

Complete Learning & Practice Guide

From Zero to Writing Real Pipelines

Install | Configure | Freestyle Jobs | Declarative Pipelines | Docker | Agents | Best Practices

Prepared for: Pavan | Cloud & DevOps Engineer | Accenture Interview Prep

■ Table of Contents

Chapter 1 What is Jenkins? — Core Concepts & Architecture

Chapter 2 Installing Jenkins — Docker & Ubuntu Methods

Chapter 3 Jenkins UI Tour — Understanding the Dashboard

Chapter 4 Freestyle Jobs — Your First Build

Chapter 5 Declarative Pipeline — The Modern Way

Chapter 6 Jenkinsfile Deep Dive — Every Keyword Explained

Chapter 7 Pipeline Stages in Detail — Build, Test, Deploy

Chapter 8 Jenkins Agents & Distributed Builds

Chapter 9 Docker in Jenkins — Build & Push Images

Chapter 10 Credentials & Secrets Management

Chapter 11 Jenkins Plugins — Must-Know List

Chapter 12 Shared Libraries — Reusable Pipeline Code

Chapter 13 Notifications — Slack, Email Alerts

Chapter 14 Common Errors & How to Fix Them

Chapter 15 Practice Labs — Hands-On Exercises

Chapter 16 Interview Questions & Answers


Chapter 1 — What is Jenkins? Core Concepts & Architecture

What is Jenkins?
Jenkins is an open-source automation server written in Java. It is the most widely used CI/CD tool in the world with over 1,800
plugins. Jenkins automates the process of building, testing, and deploying software so developers don't have to do it manually
every time they push code. Think of Jenkins as a robot that watches your code repository and automatically runs tasks
whenever code changes.

ANAL Real-world analogy: Jenkins is like a factory assembly line. When a developer pushes code (raw material), Jenkins picks it
OGY up, builds it, tests it, and ships it to production — automatically, every single time.

Jenkins Architecture — Master & Agent

Component What It Does Analogy

Jenkins Controller Main server. Manages jobs, UI, scheduling, plugins. Does NOT Factory Manager
(Master) run builds in production.

Jenkins Agent Worker machine that actually executes the build steps. Can be Factory Worker
(Node/Slave) any machine.

Executor A single build slot on an agent. One executor = one job at a Worker's Hands
time. Agents can have many.

Plugin Extends Jenkins with extra features — Git, Docker, Slack, AWS, Tool Add-ons
etc. 1,800+ available.

Jenkinsfile Pipeline defined as code, stored in your Git repo. The blueprint Recipe / Instruction Sheet
for your build.

Workspace Folder on the agent where your code is checked out and build Worker's Desk
happens.

Blue Ocean Modern visual UI for Jenkins pipelines. Shows stages as swim Dashboard Screen
lanes.

How Jenkins Works — The Flow


1. Developer pushes code to GitHub / GitLab / Bitbucket
2. GitHub sends a Webhook notification to Jenkins
3. Jenkins Controller receives the event and schedules a build
4. Controller assigns the build to a free Agent (Node)
5. Agent checks out your code into a workspace folder
6. Agent runs each stage: Build → Test → Package → Deploy
7. Results are sent back to Jenkins Controller
8. Jenkins displays pass/fail, logs, test reports in the UI
9. Notifications sent to Slack / Email based on result

Jenkins vs GitHub Actions — Key Difference

Point Jenkins GitHub Actions

Hosting Self-hosted on YOUR server Cloud-hosted by GitHub

Setup Manual install & configure Just write a YAML file

Cost Free but needs a server Free tier + paid minutes


Flexibility Extremely flexible Limited to GitHub ecosystem

Plugins 1,800+ plugins 50,000+ marketplace actions

Startups, open source, modern


Used by Enterprises, large teams teams

Pipeline syntax Groovy (Jenkinsfile) YAML (.github/workflows/)


Chapter 2 — Installing Jenkins

Method 1 — Docker (Recommended for Learning)


This is the fastest way. Run Jenkins inside a Docker container. No Java install needed.

Docker Install Commands


# Step 1: Run Jenkins in Docker

docker run -d \

-p 8080:8080 \

-p 50000:50000 \

-v jenkins_home:/var/jenkins_home \

--name jenkins \

jenkins/jenkins:lts

# Step 2: Get the initial admin password

docker exec jenkins cat /var/jenkins_home/secrets/initialAdminPassword

# Step 3: Open browser

# Go to: [Link]

# Paste the password from Step 2

-d means run in background (detached). -p 8080:8080 maps port 8080 on your machine to Jenkins. -v
PORT
jenkins_home:/var/jenkins_home saves all Jenkins data so it persists even if container restarts.

Method 2 — Ubuntu/Debian Server Install


Ubuntu Install Commands
# Step 1: Install Java (Jenkins needs Java to run)

sudo apt update

sudo apt install -y fontconfig openjdk-17-jre

java -version # Should show: openjdk version 17...

# Step 2: Add Jenkins repository key

sudo wget -O /usr/share/keyrings/[Link] \

[Link]

# Step 3: Add Jenkins to apt sources

echo "deb [signed-by=/usr/share/keyrings/[Link]] \

[Link] binary/" | \

sudo tee /etc/apt/[Link].d/[Link] > /dev/null

# Step 4: Install Jenkins

sudo apt update

sudo apt install -y jenkins

# Step 5: Start Jenkins service

sudo systemctl start jenkins

sudo systemctl enable jenkins # Auto-start on reboot

# Step 6: Get admin password

sudo cat /var/lib/jenkins/secrets/initialAdminPassword

# Open: [Link]

First-Time Setup Steps


1 Unlock Jenkins

Go to [Link]

Paste the initialAdminPassword you copied

2 Install Plugins

Click 'Install suggested plugins' — this installs Git, Pipeline, etc.

Wait 2-3 minutes for all plugins to download

3 Create Admin User

Fill in: username, password, full name, email

Click 'Save and Continue'

4 Set Jenkins URL

Keep default: [Link]

Click 'Save and Finish'

5 Start Using Jenkins

Click 'Start using Jenkins'

You're now on the Jenkins Dashboard!


Chapter 3 — Jenkins UI Tour

Dashboard Overview — What Every Section Means

UI Element What It Is What You Do Here

New Item Create button (top left) Create a new Job or Pipeline

Build Queue Right sidebar Shows jobs waiting to run

Build Executor Status Right sidebar Shows what's running right now on each agent

Job List Center of dashboard All your jobs and their last build status

Build History Left sidebar on job page List of all past builds with pass/fail

Console Output Inside each build The actual terminal output — use to debug
failures

Manage Jenkins Left sidebar on dashboard Settings, plugins, nodes, security

Credentials Under Manage Jenkins Where you store API keys, passwords, SSH keys

Nodes Under Manage Jenkins See and add Jenkins agents

Plugin Manager Under Manage Jenkins Install / update / remove plugins

Build Status Colors — What They Mean

Color / Icon Status Meaning

Blue / Checkmark SUCCESS All stages passed. Build worked perfectly.

Red / X FAILURE A stage failed. Check Console Output for error.

Yellow / Warning UNSTABLE Build ran but test failures were found.

Grey / Dashed ABORTED Build was manually stopped or timed out.

Blinking Blue RUNNING Build is currently in progress.

Grey / Not run NOT BUILT Job was never triggered or skipped by condition.
Chapter 4 — Freestyle Jobs — Your First Build

What is a Freestyle Job?


A Freestyle Job is the simplest type of Jenkins job. You configure it through the UI by filling in form fields — no code needed.
It is great for learning Jenkins basics but for real projects you will use Pipelines (Chapter 5). Think of it as 'click to configure'
vs Pipeline which is 'code to configure'.

Creating Your First Freestyle Job — Step by Step

1 Create New Job

Click 'New Item' on the left sidebar

Enter a name: my-first-job

Select 'Freestyle project'

Click OK

2 Configure Source Code

In 'Source Code Management' section — select Git

Enter Repository URL: [Link]

If private repo: click 'Add' under Credentials and add your GitHub token

Branch: */main

3 Set Build Trigger

In 'Build Triggers' section

Check 'GitHub hook trigger for GITScm polling' — auto build on push

Or check 'Poll SCM' and enter: H/5 * * * * (check every 5 minutes)

4 Add Build Step

In 'Build Steps' section — click 'Add build step'

Select 'Execute shell'

Type your commands: echo 'Hello Jenkins!' and pwd and ls -la

5 Save and Run

Click 'Save' at the bottom

Click 'Build Now' on the left sidebar

Click the build number that appears under 'Build History'

Click 'Console Output' to see your commands running!

Freestyle Job — Build Step Examples


Shell Commands for Freestyle Job
# Example 1: Print system info

echo 'Build started'

echo 'Current directory:'

pwd

echo 'Files in workspace:'

ls -la

# Example 2: Run Python tests

pip install -r [Link]

python -m pytest tests/ -v

# Example 3: Build a Docker image

docker build -t my-app:latest .

docker images | grep my-app


Chapter 5 — Declarative Pipeline — The Modern Way

What is a Declarative Pipeline?


A Declarative Pipeline is a Jenkins pipeline written as code in a file called Jenkinsfile and stored in your Git repository. This is
the modern, recommended way to use Jenkins. Instead of clicking around the UI, you write your entire pipeline as code —
just like GitHub Actions uses YAML files. This means your pipeline is versioned, reviewable, and shareable with your team.

KEY Pipeline as Code = your pipeline lives in your repo alongside your application code. When you change the Jenkinsfile, the
IDEA pipeline changes. No clicking in the UI required.

Creating a Pipeline Job — Step by Step

1 Create Pipeline Job

Click 'New Item'

Enter name: my-pipeline

Select 'Pipeline'

Click OK

2 Point to Your Jenkinsfile

Scroll to 'Pipeline' section at the bottom

Definition: select 'Pipeline script from SCM'

SCM: select Git

Repository URL: your GitHub repo URL

Script Path: Jenkinsfile (default — it looks for this file in your repo root)

3 Create Jenkinsfile in Your Repo

In your GitHub repo, create a file called: Jenkinsfile (no extension)

Paste the pipeline code (see Chapter 6)

Commit and push to main branch

4 Run the Pipeline

Back in Jenkins, click 'Build Now'

You will see stages appear as colored boxes

Click any stage box to see its logs

Green = passed, Red = failed


Chapter 6 — Jenkinsfile Deep Dive — Every Keyword Explained

Skeleton Structure — Every Jenkinsfile Has This


Jenkinsfile Skeleton
// This is the Jenkinsfile — store it in your repo root

pipeline { // Every declarative pipeline starts with this

agent any // Run on any available Jenkins agent

environment { // Define variables available to all stages

APP_NAME = 'my-app'

VERSION = '1.0.0'

options { // Pipeline-level settings

timeout(time: 1, unit: 'HOURS') // Fail if takes > 1 hour

disableConcurrentBuilds() // Only one build at a time

triggers { // What automatically starts this pipeline

githubPush() // Trigger on every GitHub push

stages { // All your stages go inside here

stage('Build') { // One stage

steps { // Steps inside the stage

echo 'Building...'

stage('Test') {

steps {

echo 'Testing...'

post { // Runs after ALL stages complete

always { echo 'Always runs' }

success { echo 'Only if all stages passed' }

failure { echo 'Only if something failed' }

Every Keyword — What It Does

Keyword What It Does When You Use It

pipeline {} Wrapper for entire declarative pipeline Always — every Jenkinsfile starts
with this

agent any Run on any available agent/node Default choice — use unless you
need specific agent

agent none No global agent — each stage picks its own When different stages need
different environments
agent { label 'linux' } Run only on agents with this label When you have dedicated build
servers

agent { docker 'python:3.11' } Run inside a Docker container When you want clean isolated
environments

environment {} Define environment variables Store config values, version


numbers, flags

stages {} Container for all your stages Always — wraps your stage()
blocks

stage('Name') {} One logical step in pipeline Group related commands —


Build, Test, Deploy

steps {} Container for commands inside a stage Always inside a stage()

echo 'text' Print text to console output Debugging, logging progress


messages

sh 'command' Run a shell command on Linux/Mac Most common step — runs any
bash command

bat 'command' Run a Windows batch command Only on Windows agents

script {} Run Groovy code inside declarative pipeline When you need if/else logic or
loops

when {} Conditional — stage only runs if condition is true Deploy only on main branch, etc.

when { branch 'main' } Run stage only when on main branch Production deployments

when { expression {} } Run stage based on any custom condition Complex conditions using
variables

parallel {} Run multiple stages at the same time Speed up pipeline — run tests in
parallel

options {} Pipeline settings block Timeouts, concurrent build limits,


logs

triggers {} What automatically starts this pipeline GitHub webhook, scheduled cron,
upstream job

post {} Runs after pipeline finishes Notifications, cleanup, always


send alerts

always {} Inside post — runs regardless of result Workspace cleanup, always-send


reports

success {} Inside post — runs only on success Success Slack message, deploy
notifications

failure {} Inside post — runs only on failure Alert team, rollback, page on-call

input {} Pause pipeline and wait for human approval Manual gate before production
deployment

withCredentials {} Inject secrets safely into steps AWS keys, Docker registry
passwords

cleanWs() Delete workspace after build Keep agents clean — prevents


disk full errors

junit 'path' Parse and publish JUnit test results After running tests — shows
pass/fail in UI
archiveArtifacts Save files from build as downloadable artifacts Save JAR files, test reports, built
binaries
Chapter 7 — Complete Pipeline Stages — Build, Test, Deploy

Full Production-Level Jenkinsfile


Complete Production Jenkinsfile
pipeline {

agent any

environment {

APP_NAME = 'flask-api'

DOCKER_REPO = 'yourdockerhub/flask-api'

DEPLOY_ENV = 'staging'

options {

timeout(time: 1, unit: 'HOURS') // Kill if stuck

disableConcurrentBuilds() // No parallel runs

buildDiscarder(logRotator(numToKeepStr: '10')) // Keep 10 builds

triggers {

githubPush() // Auto-trigger on every git push

stages {

// ■■ STAGE 1: Checkout ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■

stage('Checkout') {

steps {

checkout scm // Checks out code from configured Git repo

sh 'git log --oneline -5' // Show last 5 commits in logs

// ■■ STAGE 2: Install Dependencies ■■■■■■■■■■■■■■■■■■

stage('Install') {

steps {

sh 'pip install -r [Link]'

// ■■ STAGE 3: Lint & Code Quality ■■■■■■■■■■■■■■■■■■■

stage('Lint') {

steps {

sh 'flake8 . --max-line-length=88'

// ■■ STAGE 4: Run Tests (Parallel) ■■■■■■■■■■■■■■■■■■

stage('Test') {

parallel {

stage('Unit Tests') {

steps {
sh 'python -m pytest tests/unit -v --junitxml=[Link]'

stage('Integration Tests') {

steps {

sh 'python -m pytest tests/integration -v'

post {

always {

junit '[Link]' // Publish test results to UI

// ■■ STAGE 5: Build Docker Image ■■■■■■■■■■■■■■■■■■■■■

stage('Docker Build') {

when { branch 'main' } // Only run on main branch

steps {

script {

def imageTag = "${DOCKER_REPO}:${env.BUILD_NUMBER}"

sh "docker build -t ${imageTag} ."

sh "docker tag ${imageTag} ${DOCKER_REPO}:latest"

// ■■ STAGE 6: Push to Registry ■■■■■■■■■■■■■■■■■■■■■■

stage('Docker Push') {

when { branch 'main' }

steps {

withCredentials([usernamePassword(

credentialsId: 'dockerhub-creds',

usernameVariable: 'DOCKER_USER',

passwordVariable: 'DOCKER_PASS'

)]) {

sh 'echo $DOCKER_PASS | docker login -u $DOCKER_USER --password-stdin'

sh "docker push ${DOCKER_REPO}:${BUILD_NUMBER}"

sh "docker push ${DOCKER_REPO}:latest"

// ■■ STAGE 7: Deploy to Staging ■■■■■■■■■■■■■■■■■■■■■

stage('Deploy Staging') {

when { branch 'main' }

steps {

sh 'docker-compose -f [Link] up -d'


}

// ■■ STAGE 8: Manual Approval ■■■■■■■■■■■■■■■■■■■■■■■

stage('Approve Production') {

when { branch 'main' }

input {

message 'Deploy to production?'

ok 'Yes, deploy now!'

submitter 'admin,lead-dev' // Only these users can approve

steps {

echo 'Production deployment approved!'

// ■■ STAGE 9: Deploy to Production ■■■■■■■■■■■■■■■■■

stage('Deploy Production') {

when { branch 'main' }

steps {

sh './scripts/[Link]'

// ■■ POST: Notifications & Cleanup ■■■■■■■■■■■■■■■■■■■

post {

always {

cleanWs() // Delete workspace — keep agent disk clean

success {

slackSend(color: 'good',

message: "SUCCESS: ${JOB_NAME} #${BUILD_NUMBER}")

failure {

slackSend(color: 'danger',

message: "FAILED: ${JOB_NAME} #${BUILD_NUMBER}")

emailext(to: 'team@[Link]',

subject: 'Build Failed',

body: 'Check Jenkins: ${BUILD_URL}')

}
Chapter 8 — Jenkins Agents & Distributed Builds

What is a Jenkins Agent?


A Jenkins Agent (also called Node or Slave) is any machine that Jenkins uses to run builds. The Controller (master) manages
everything, but actual build work happens on Agents. You can have many agents — Linux agents, Windows agents, Docker
agents, cloud agents. Each agent is labeled so Jenkins can route the right job to the right machine.

Agent Types — Syntax Examples


Agent Configuration Syntax
// Type 1: Any available agent (simplest)

agent any

// Type 2: No global agent (each stage defines its own)

agent none

// Type 3: Agent with a specific label

agent { label 'linux-build-server' }

// Type 4: Run inside a Docker container

agent {

docker {

image 'python:3.11-slim'

args '-v /tmp:/tmp' // Optional: mount volumes

// Type 5: Different agent per stage

pipeline {

agent none // No global agent

stages {

stage('Build on Linux') {

agent { label 'linux' }

steps { sh 'make build' }

stage('Test on Windows') {

agent { label 'windows' }

steps { bat '[Link]' }

Adding a New Agent Node — Step by Step

1 Go to Node Management

Jenkins Dashboard → Manage Jenkins → Manage Nodes and Clouds

Click 'New Node'

2 Configure the Node

Node name: linux-agent-1


Select: Permanent Agent → Click OK

Remote root directory: /home/jenkins (folder on agent machine)

Labels: linux (used in Jenkinsfile to target this agent)

Launch method: Launch agent by connecting to the controller

3 Connect the Agent

Save the node — Jenkins gives you a command to run on the agent machine

On the agent machine, run the provided java -jar [Link] command

Agent will appear as 'online' in Jenkins UI


Chapter 9 — Docker in Jenkins — Build & Push Images

Setup: Give Jenkins Access to Docker


Allow Jenkins to Use Docker
# On the Jenkins server / agent machine:

# Add jenkins user to docker group so it can run docker commands

sudo usermod -aG docker jenkins

# Restart Jenkins to apply group change

sudo systemctl restart jenkins

# Verify: run a test build with this command

docker ps

# If it works without 'sudo', Jenkins can now run Docker

Build and Push to Docker Hub


Build and Push to Docker Hub
// Step 1: Store your Docker Hub credentials in Jenkins

// Go to: Manage Jenkins → Credentials → Add Credentials

// Kind: Username with Password

// Username: your Docker Hub username

// Password: your Docker Hub password or access token

// ID: dockerhub-creds (this is what you reference in Jenkinsfile)

// Step 2: Use in Jenkinsfile

stage('Build & Push Docker Image') {

steps {

script {

def image = "yourusername/my-app:${BUILD_NUMBER}"

// Build the image

sh "docker build -t ${image} ."

// Login and push

withCredentials([usernamePassword(

credentialsId: 'dockerhub-creds',

usernameVariable: 'USER',

passwordVariable: 'PASS'

)]) {

sh 'echo $PASS | docker login -u $USER --password-stdin'

sh "docker push ${image}"

Build and Push to AWS ECR


Push to Amazon ECR
// Store AWS credentials in Jenkins:

// Manage Jenkins → Credentials → Add → AWS Credentials


// Access Key ID + Secret Access Key

// ID: aws-creds

stage('Push to Amazon ECR') {

environment {

AWS_REGION = 'ap-south-1'

ECR_ACCOUNT = '123456789012'

ECR_REPO = 'my-flask-api'

steps {

withCredentials([[

$class: 'AmazonWebServicesCredentialsBinding',

credentialsId: 'aws-creds'

]]) {

script {

def ecrUrl = "${ECR_ACCOUNT}.[Link].${AWS_REGION}.[Link]"

def fullTag = "${ecrUrl}/${ECR_REPO}:${BUILD_NUMBER}"

// Login to ECR

sh "aws ecr get-login-password --region ${AWS_REGION} | \\

docker login --username AWS --password-stdin ${ecrUrl}"

// Build and push

sh "docker build -t ${fullTag} ."

sh "docker push ${fullTag}"

}
Chapter 10 — Credentials & Secrets Management

Types of Credentials in Jenkins

Credential Type Use Case Jenkins Kind

Username + Password Docker Hub, GitHub, any login Username with password

Secret Text API tokens, single string secrets Secret text

SSH Private Key SSH into servers, GitHub SSH SSH Username with private key

AWS Credentials AWS Access Key + Secret Key AWS Credentials (needs plugin)

Certificate SSL certs, keystore files Certificate

Any file you don't want in code (.env,


Secret File kubeconfig) Secret file

Adding Credentials — Step by Step

1 Open Credentials Manager

Jenkins Dashboard → Manage Jenkins → Credentials

Click on 'System' then 'Global credentials (unrestricted)'

Click 'Add Credentials' on the left

2 Fill in the Form

Kind: select the type (e.g. Username with password)

Username: your username

Password: your password or token

ID: give it a name like 'github-token' — this is how you reference it in Jenkinsfile

Description: optional but helpful

Click OK

3 Use in Jenkinsfile

Use withCredentials() block — Jenkins injects the secret as an env variable

Secret is NEVER printed in logs — Jenkins masks it automatically

See code examples below

withCredentials Examples
// Example 1: Username + Password

withCredentials([usernamePassword(

credentialsId: 'github-token',

usernameVariable: 'GIT_USER',

passwordVariable: 'GIT_TOKEN'
)]) {

sh 'git clone [Link]

// Example 2: Secret Text (single token)

withCredentials([string(

credentialsId: 'slack-webhook-url',

variable: 'SLACK_URL'

)]) {

sh "curl -X POST -d 'text=Build done' $SLACK_URL"

// Example 3: SSH Key

withCredentials([sshUserPrivateKey(

credentialsId: 'deploy-server-key',

keyFileVariable: 'SSH_KEY',

usernameVariable: 'SSH_USER'

)]) {

sh 'ssh -i $SSH_KEY $SSH_USER@[Link] uptime'

NEVER hardcode passwords or tokens in your Jenkinsfile. Always store them in Jenkins Credentials and use
WARN
withCredentials() to inject them. If you accidentally commit a secret to Git, rotate it immediately.
Chapter 11 — Jenkins Plugins — Must-Know List

How to Install Plugins


Go to: Manage Jenkins → Plugin Manager → Available tab → Search by name → Check the box → Click 'Install without
restart'. Most plugins work immediately.

Essential Plugins — Install All of These

Plugin Name What It Does Why You Need It

Git Plugin Connects Jenkins to GitHub/GitLab/Bitbucket Required for any project with Git

Pipeline Enables Jenkinsfile declarative pipelines Required for modern pipelines

Blue Ocean Modern visual UI for pipelines Makes stages visible and easy to
debug

Docker Pipeline Build/push Docker images in Jenkinsfile using For Docker-based builds
[Link]()

Docker Plugin Use Docker containers as build agents Run each stage in clean container

AWS Credentials Plugin Store and use AWS access keys Required for any AWS deployment

Amazon ECR Plugin Push Docker images to Amazon ECR For AWS container deployments

Slack Notification Plugin Send build result messages to Slack Team notifications on pass/fail

Email Extension Plugin Send rich HTML emails on build events Email alerts with full build logs

GitHub Integration Plugin GitHub webhooks trigger builds automatically Auto-trigger on push

Credentials Plugin Manage and inject secrets safely Always needed — installed by
default

Workspace Cleanup Plugin Adds cleanWs() step to delete workspace Keep agents disk-clean

JUnit Plugin Parse and display test results in UI Show test pass/fail in build page

Timestamper Plugin Add timestamps to console output Know exactly when each step ran

Build Timeout Plugin Kill builds that hang too long Prevent stuck builds blocking agents

SSH Agent Plugin Use SSH keys in pipeline steps Deploy to remote servers via SSH
Chapter 12 — Shared Libraries — Reusable Pipeline Code

What is a Shared Library?


A Shared Library is reusable Groovy code that multiple Jenkinsfiles can import and use. Instead of copying the same Docker
build logic into 10 different Jenkinsfiles, you write it once in a Shared Library and every project imports it with one line. This is
exactly like a Python package or npm module — write once, use everywhere.

Shared Library Folder Structure


Library Structure
# Your shared library Git repo structure:

my-jenkins-library/

vars/ # Simple functions called in pipelines

[Link]

[Link]

[Link]

src/ # Complex Groovy classes

org/company/[Link]

resources/ # Non-Groovy files (shell scripts, templates)

[Link]

vars/ Functions
// vars/[Link]

def call(String imageName, String tag = 'latest') {

sh "docker build -t ${imageName}:${tag} ."

sh "docker push ${imageName}:${tag}"

echo "Pushed ${imageName}:${tag} successfully"

// ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■

// vars/[Link]

def call(String message, String color = 'good') {

slackSend(color: color, message: message)

Using the Library in Jenkinsfile


// Jenkinsfile that uses the shared library

@Library('my-jenkins-library') _ // Import with @Library annotation

pipeline {

agent any

stages {

stage('Build & Push') {

steps {

// Call the shared library function directly

dockerBuildPush('myrepo/my-app', env.BUILD_NUMBER)

post {
success { sendSlackNotify('Build passed!') }

failure { sendSlackNotify('Build FAILED!', 'danger') }

Registering Library in Jenkins


Go to: Manage Jenkins → Configure System → Global Pipeline Libraries → Add Library → Set name (e.g. my-jenkins-library)
→ Source: your Git repo URL → Default version: main. Now any Jenkinsfile can use @Library('my-jenkins-library') _
Chapter 13 — Notifications — Slack & Email Alerts

Slack Notifications Setup

1 Create Slack App & Webhook

Go to [Link]/apps → Create New App

Add 'Incoming Webhooks' feature → Activate it

Click 'Add New Webhook to Workspace' → Select your channel

Copy the Webhook URL (looks like: [Link]

2 Store Webhook in Jenkins

Manage Jenkins → Credentials → Add

Kind: Secret text

Secret: paste your webhook URL

ID: slack-webhook

3 Install Slack Plugin

Manage Jenkins → Plugin Manager → Search 'Slack Notification'

Install and restart

Manage Jenkins → Configure System → Slack → Enter workspace + token

Slack & Email in Jenkinsfile


// Slack notification in post block

post {

success {

slackSend(

color: 'good',

message: "SUCCESS: Job '${JOB_NAME}' Build #${BUILD_NUMBER}\n" +

"Branch: ${GIT_BRANCH}\n" +

"URL: ${BUILD_URL}"

failure {

slackSend(

color: 'danger',

message: "FAILED: Job '${JOB_NAME}' Build #${BUILD_NUMBER}\n" +

"Check logs: ${BUILD_URL}console"

// Email notification

post {
failure {

emailext(

to: 'team@[Link]',

subject: "Jenkins Build FAILED: ${JOB_NAME} #${BUILD_NUMBER}",

body: "Build failed. Check: ${BUILD_URL}\n\n${BUILD_LOG}"

}
Chapter 14 — Common Errors & How to Fix Them

Error Cause Fix

No such DSL method 'docker' Docker Pipeline plugin not installed Install Docker Pipeline plugin in Plugin
Manager

Permission denied ([Link]) Jenkins user not in docker group Run: sudo usermod -aG docker jenkins
&& restart

unable to connect to GitHub: GitHub webhook URL wrong or firewall Check Jenkins URL in Manage Jenkins
Connection refused blocking → Configure System. Use ngrok for
local testing.

Script not permitted to use Groovy sandbox blocking your code Go to: Manage Jenkins → In-process
staticMethod Script Approval → Approve the method

No credentials found for Credential ID doesn't match what's stored Check Manage Jenkins → Credentials
credentialsId: 'xyz' — confirm exact ID spelling

checkout scm: null Pipeline job not linked to Git SCM In job config, set Pipeline from SCM and
add repo URL

ERROR: No such file: Jenkinsfile Script Path is wrong or file not committed Check Script Path field matches actual
file name + path in repo

Workspace is locked Previous build still running or crashed Manage Jenkins → Nodes →
Disconnect & reconnect agent

[Link]: remote file Agent disk full Free disk space on agent. Enable
operation failed cleanWs() in post block.

Host key verification failed (SSH) SSH host not in known_hosts On agent, run: ssh-keyscan host >>
~/.ssh/known_hosts

Build keeps queuing but never No available executors / agents offline Check Manage Jenkins → Nodes —
starts bring offline agents online
Chapter 15 — Practice Labs — Hands-On Exercises

Lab 1 Hello World Pipeline • Est. time: 30 mins

Goal: Install Jenkins locally and run your first Jenkinsfile

1. Install Jenkins using Docker (see Chapter 2)

2. Create a new Pipeline job called hello-world

3. Write a Jenkinsfile with 3 stages: Greet, Show Info, Done

4. Each stage should print a message with echo

5. Run the pipeline and see all 3 stages pass (green boxes)

6. Look at Console Output — understand every line

Lab 2 GitHub Integration • Est. time: 45 mins

Goal: Auto-trigger Jenkins build when you push code to GitHub

1. Create a public GitHub repo with a simple README

2. Add a Jenkinsfile to the repo (echo 'Code pushed!' in 2 stages)

3. In Jenkins, create a Pipeline job pointing to your GitHub repo

4. Install GitHub Integration Plugin

5. Set up a webhook in GitHub: Settings → Webhooks → Add

6. Push a commit to GitHub and watch Jenkins auto-trigger the build

Lab 3 Docker Build & Push • Est. time: 1 hour

Goal: Build a Docker image of your Flask app and push to Docker Hub

1. Create a simple Flask app ([Link] with /health endpoint)

2. Write a Dockerfile for it

3. Add Docker Hub credentials to Jenkins (Chapter 10)

4. Write a Jenkinsfile with stages: Checkout, Build Image, Push Image

5. Run the pipeline — verify image appears on Docker Hub

6. Pull the image locally and run it to confirm it works

Lab 4 Parallel Test Stages • Est. time: 45 mins

Goal: Run unit tests and linting in parallel to speed up the pipeline

1. Add pytest and flake8 to your Flask project

2. Write 2 simple unit tests in tests/test_app.py

3. Update Jenkinsfile to add a parallel Test stage

4. Stage 1 (parallel): Run flake8 linting

5. Stage 2 (parallel): Run pytest unit tests


6. Notice both run at the same time and total time is faster

Lab 5 Manual Approval Gate • Est. time: 30 mins

Goal: Add a human approval step before deployment

1. Add a Deploy Staging stage that echoes 'Deployed to staging!'

2. After it, add a stage with input{} block asking for approval

3. Add a Deploy Production stage that only runs after approval

4. Run the pipeline — it will pause and wait for your click

5. Click 'Yes, deploy now!' and watch production stage run

6. Try clicking 'Abort' and see what happens to the pipeline

Lab 6 Slack Notifications • Est. time: 45 mins

Goal: Receive Slack messages when builds pass or fail

1. Create a free Slack workspace if you don't have one

2. Create an Incoming Webhook (Chapter 13 steps)

3. Store webhook URL in Jenkins Credentials as secret text

4. Add post{} block to your pipeline with success and failure blocks

5. Run a successful build — verify Slack message in your channel

6. Intentionally break a step (sh 'exit 1') — verify failure message


Chapter 16 — Interview Questions & Answers

Q1: What is Jenkins and what problem does it solve?

A: Jenkins is an open-source automation server used for CI/CD. It solves the problem of manual, error-prone software builds and
deployments. Without Jenkins, every developer runs builds manually, integration conflicts pile up, and deployments are risky.
Jenkins automates the entire process: detect code push → build → test → deploy. This gives teams faster feedback and reliable,
repeatable deployments.

Q2: What is the difference between a Freestyle Job and a Pipeline Job?

A: A Freestyle Job is configured through the Jenkins UI by filling form fields — no code needed. Easy for beginners but hard to
version control. A Pipeline Job is defined as code in a Jenkinsfile stored in your Git repo. It supports complex logic, parallel stages,
conditions, and is the modern recommended approach. The key advantage of Pipeline: it is versioned, reviewable, and shareable
just like your application code.

Q3: What is a Jenkinsfile?

A: A Jenkinsfile is a text file written in Groovy DSL that defines your entire CI/CD pipeline as code. It lives in the root of your Git
repository alongside your application code. It contains all pipeline stages, steps, conditions, and post-build actions. When Jenkins
detects a change in your repo, it reads the Jenkinsfile and executes the pipeline automatically.

Q4: Explain Jenkins Master-Agent architecture.

A: The Jenkins Controller (master) is the main server that manages jobs, the UI, scheduling, and plugins. It does NOT run builds
itself in production. Agents (nodes) are worker machines that execute the actual build steps. When a build is triggered, the
Controller assigns it to a free Agent. The Agent checks out code, runs the stages, and reports results back to the Controller. This
allows Jenkins to scale — many agents running builds in parallel.

Q5: What is the 'post' block in a Jenkinsfile?

A: The post block defines actions to run after all pipeline stages complete, regardless of success or failure. It has conditions:
always{} runs every time, success{} only runs if all stages passed, failure{} only runs if something failed, unstable{} runs if tests
failed but build succeeded. Typical use: always cleanWs() to delete workspace, success send a Slack green message, failure send
a Slack red alert and email the team.

Q6: How do you handle secrets and passwords in Jenkins?

A: Never hardcode secrets in Jenkinsfile. Store them in Jenkins Credentials Manager under Manage Jenkins → Credentials.
Supported types: Username+Password, Secret Text, SSH Keys, AWS Credentials. In the Jenkinsfile use withCredentials() block
which injects the secret as an environment variable. Jenkins automatically masks the secret value in logs — even if you accidentally
echo it, it appears as ****.

Q7: What is the 'when' directive in Jenkins Pipeline?

A: The when directive makes a stage conditional — it only runs when the condition is true. Common examples: when { branch 'main'
} runs only on main branch, when { expression { return [Link] == 'yes' } } runs based on a custom condition. This is how
you deploy to production only from the main branch while feature branches only run tests.

Q8: What is the 'input' step and why is it used?


A: The input step pauses the pipeline and waits for a human to click a button to continue. It is used as a manual approval gate
before deploying to production. You can specify who is allowed to approve using the submitter field (e.g. submitter:
'admin,lead-dev'). If no one approves within the timeout period, the build is aborted automatically.

Q9: What Jenkins plugins do you know and what do they do?

A: Key plugins: Git Plugin connects Jenkins to GitHub/GitLab. Pipeline plugin enables Jenkinsfile support. Blue Ocean gives a
visual pipeline UI. Docker Pipeline lets you build/push images in code. AWS Credentials stores AWS keys. Slack Notification sends
build alerts to Slack. Email Extension sends rich HTML emails. GitHub Integration enables automatic webhook triggers. Workspace
Cleanup adds cleanWs() to delete workspace after builds.

Q10: How do you trigger a Jenkins build automatically on a code push?

A: Two methods: 1) GitHub Webhook — In GitHub repo Settings, add a Webhook pointing to
[Link] In Jenkins job, check 'GitHub hook trigger for GITScm polling'. When developer pushes
code, GitHub instantly notifies Jenkins. 2) Poll SCM — Jenkins checks the repo every N minutes using a cron expression. Less
efficient than webhooks but works without public Jenkins URL.
Quick Reference — Commands & Cheat Sheet

Jenkins Environment Variables — Always Available in Pipelines

Variable Value / Example

BUILD_NUMBER Sequential build count: 1, 2, 3...

BUILD_URL Full URL to this build: [Link]

JOB_NAME Name of the job: my-pipeline

WORKSPACE Path to workspace folder: /var/jenkins/workspace/my-pipeline

GIT_BRANCH Current branch: origin/main

GIT_COMMIT Full git commit SHA: a1b2c3d4...

JENKINS_URL Base Jenkins URL: [Link]

NODE_NAME Name of agent running this build: linux-agent-1

BUILD_ID Same as BUILD_NUMBER

Cron Trigger Syntax — pollSCM and Scheduled Builds


Cron Trigger Examples
triggers {

// Format: Minute Hour DayOfMonth Month DayOfWeek

// H means 'hash' — Jenkins spreads load automatically

pollSCM('H/5 * * * *') // Poll every 5 minutes

cron('0 2 * * *') // Run at 2am every day

cron('0 9 * * 1-5') // 9am Monday to Friday

cron('H H * * 0') // Once a week on Sunday

cron('@daily') // Every day at midnight

cron('@weekly') // Every Sunday at midnight

Most Used Pipeline Steps — Quick List

Step What It Does

sh 'command' Run any bash/shell command on Linux

bat 'command' Run Windows batch command

echo 'message' Print message to console output

checkout scm Check out code from configured Git repo

cleanWs() Delete entire workspace (use in post always{})

sleep(time: 30, unit: 'SECONDS') Pause pipeline for specified time

error('message') Intentionally fail the build with a message

unstable('message') Mark build unstable (yellow) without failing

[Link] = 'SUCCESS' Manually set build result in script{}


env.MY_VAR = 'value' Set an environment variable dynamically

readFile('filename') Read contents of a file into a string

writeFile file:'[Link]', text:'hello' Write a string to a file

archiveArtifacts 'dist/**' Save build output files as artifacts

junit 'test-results/*.xml' Parse and publish JUnit test results

stash name:'app', includes:'dist/**' Save files to pass to another stage

unstash 'app' Retrieve files saved with stash

Start with Lab 1 today — install Jenkins in Docker and run your first pipeline. Each lab builds on the previous one. By
Lab 6 you will have a fully working CI/CD pipeline with Docker, GitHub integration, and Slack notifications. That is
exactly what Accenture wants to see. You've got this, Pavan!

You might also like