09 - Jenkins Running Notes
09 - Jenkins Running Notes
CI CD Server (Jenkins)
=======================
CI : Continuous Integration
CD : Continuos Delivery
===========================
What is Build & Deployment
===========================
=> In single day multipe times code will be committed to git hub repository from
Development team so multiple times we have to perform build and deployment process.
Note: If we do build and deployment process manually then it is time taking process
and error prone.
=> To overcome above problems, we need to automate Project Build and Deployment
process.
=> To automate project build and deployment process we will use JENKINS.
===================
What is Jenkins ?
===================
=> Using Jenkins we can deploy any type of project (ex: java, python, dot net,
react, angular).
================
Jenkins Setup
================
URL : http://ec2-public-ip:8080/
pwd : 5fe6ddcc9db244cab6aca5ccf2d6a83a
-> Select "Install Suggested Plugins" card (it will install those plugins)
===============================
Creating First Job in Jenkins
===============================
6) Click on 'Build Number' and then click on 'Console Ouput' to see job execution
details.
$ cd /var/lib/jenkins/workspace/
7) Go to Jenkins home directory and check for the job name --> check the file
created inside the job
=========================================================
Jenkins Job with with GIT Hub Repo + Maven - Integeration
=========================================================
==================================
Maven Installation In Jenkins:
==================================
Jenkins Dashboard -> Manage Jenkins --> Global Tools Configuration -> Add maven
==================================
Sample Git Repo URLS For Practise
==================================
============================================================
JOB-2 :: Steps To Create Jenkins Job with Git Repo + Maven
============================================================
3) Access Jenkins Server Dashboard and Login with your jenkins credentials
6) Click on 'Build Number' and then click on 'Console Ouput' to see job execution
details.
=> Go to jenkins workspace and then go to job folder then goto target folder there
we see war file created.
-----------------------------------------------------------------------------------
--------------
URL : http://EC2-VM-IP:8080/exit/
=============================================================================
Job-3 :: Steps To Create Jenkins Job with Git Repo + Maven + Tomcat Server
============================================================================
1) Go to Jenkins Dashboard -> Manage Jenkins --> Manage Plugins -> Goto Available
Tab -> Search For
"Deploy To Container" Plugin -> Install without restart.
4) Run the job now using 'Build Now' option and see see 'Console Output' of job
5) Once Job Executed successfully, go to tomcat server dashboard and see
application should be displayed.
===================================================
How to Create Jenkins Jobs with Build Parameters
===================================================
=> Build Parameters are used to supply dynamic inputs to run the Job. Using Build
Parameters we can avoid hard coding.
====================================
User & Roles Management In Jenkins
====================================
=> For every Team member Jenkins login access will be provided.
Note: Every team members will have their own user account to login into jenkins.
=> Operations team members are responsible to create / edit / delete / run jenkins
jobs
=> Dev and Testing team members are only responsible to run the jenkins job.
================================================
How to create users and manage user permissions
================================================
Note: By default admin role will be available and we can create custom role based
on requirement
-> In Role we can configure what that Role assigned user can do in jenkins
=====================================
Working with User Groups in Jenkins
=====================================
=> This plugin allows you to define roles and assign them to users or groups.
=> Click "Manage Roles" and define new roles based on your requirements (e.g.,
admin, developer, tester).
=> Click "Add" to create a new role, and specify the permissions for that role.
=> After creating roles, go to "Manage Jenkins" > "Manage Users & Roles."
=> Select a user and click "Assign Roles" to add them to one or more roles.
========================================
Jenkins - Master & Slave Architecture
========================================
=> If we use single machine to run Jenkins server then burden will be increased if
we run multiple jobs at a time.
=> To execute multiple jobs paralelly we will use Master & Slave Configuration
=> Master & Slave configuration is used to reduce burden on Jenkins Server by
distributing tasks/load.
================
Jenkins Master
===============
=> The machine which contains Jenkins Server is called as Jenkins Master machine.
Note: We can run jobs on Jenkins Master machine directley but not recommended.
==============
Jenkins Slave
==============
=> The machine which is connected with 'Jenkins Master' machine is called as
'Jenkins-Slave' machine.
=> Slave Machine will recieve task from 'Master Machine' for job execution.
===============================
Step-1 : Create Jenkins Master
==============================
===============================
Step-2 : Create Jenkins Slave
===============================
$ mkdir slavenode
=====================================================
Step-3: Configure Slave Node in Jenkins Master Node
=====================================================
1) Go to Jenkins Dashboard
2) Go to Manage Jenkins
3) Go to Manage Nodes & Clouds
4) Click on 'New Node' -> Enter Node Name -> Select Permanent Agent
5) Enter Remote Root Directory ( /home/ubuntu/slavenode )
6) Enter Label name as Slave-1
7) Select Launch Method as 'Launch Agent Via SSH'
8) Give Host as 'Slave VM DNS URL'
9) Add Credentials ( Select Kind as : SSH Username with private key )
10) Enter Username as : ubuntu
11) Select Private Key as Enter Directley and add private key
12) Select Host Key Strategy as 'Manually Trusted Key Verification Strategy'
13) Click on Apply and Save (We can see configured slave)
Note: Under Generation Section of Job creation process, Select "Restrict Where This
Project Can Run" and enter Slave Nodel Label name and finish job creation.
Note: Job will be executed on Slave Node (Go to Job Console Ouput and verify
execution details)
=================
Jenkins Pipeline
=================
=> Pipeline means set of steps to automate build & deployment process.
=> Using Pipelines we can handle complex build & deployment tasks.
a) Scripted Pipeline
b) Declarative Pipeline
==============================
Jenkins Declarative Pipeline
==============================
pipeline {
agent any
stages {
stage('Git Clone') {
steps {
echo 'Cloning Repository....'
}
}
stage('Maven Build'){
steps{
echo 'Maven Build....'
}
}
stage('Tomcat Deploy'){
steps{
echo "War deployed to tomcat"
}
}
}
}
====================================
Declarative Pipeline (Git + Maven)
====================================
pipeline {
agent any
tools{
maven "Maven-3.9.4"
}
stages {
stage('Clone') {
steps {
git 'https://github.com/ashokitschool/maven-web-app.git'
}
}
stage('Build') {
steps {
sh 'mvn clean package'
}
}
}
}
==================
Scripted Pipeline
==================
node {
stage('Git Clone') {
git credentialsId: 'GIT-Credentials', url:
'https://github.com/ashokitschool/maven-web-app.git'
}
stage('Maven Build'){
def mavenHome = tool name:"Maven-3.9.4", type: "maven";
def mavenPath = "${mavenHome}/bin/mvn";
sh "${mavenPath} clean package"
}
}
##########################################
DevOps Project Setup with CI CD Pipeline
##########################################
1) Git Hub
2) Maven
3) SonarQube
4) Nexus Repo
5) Tomcat
6) Jenkins
##################
Pipeline creation
##################
========================
1) Create github stage
========================
stage('clone repo') {
=========================================================
2) Create Maven Build Stage (Add maven in global tools)
=========================================================
============================
3) Create SonarQube stage
===========================
-> Manage Jenkins -> Plugins -> Available -> Sonar Qube Scanner Plugin -> Install
it
-> Manage Jenkins -> Configure System -> Sonar Qube Servers -> Add Sonar Qube
Server
- Name : Sonar-Server-7.8
- Server URL : http://52.66.247.11:9000/ (Give your sonar
server url here)
- Add Sonar Server Token
-> Once above steps are completed, then add below stage in the pipeline
stage('SonarQube analysis') {
withSonarQubeEnv('Sonar-Server-7.8') {
def mavenHome = tool name: "Maven-3.8.6", type: "maven"
def mavenCMD = "${mavenHome}/bin/mvn"
sh "${mavenCMD} sonar:sonar"
}
}
=======================
4) Create Nexus Stage
======================
-> Run nexus VM and create nexus repository
-> Install Nexus Repository Plugin using Manage Plugins ( Plugin Name : Nexus
Artifact Uploader)
=========================
5) Create Deploy Stage
=========================
stage ('Deploy'){
sshagent(['Tomcat-Server-Agent']) {
sh 'scp -o StrictHostKeyChecking=no target/01-maven-web-app.war
[email protected]:/home/ec2-user/apache-tomcat-9.0.80/webapps'
}
}
################
Final Pipeline
################
node {
stage('Git Clone'){
git credentialsId: 'GIT-CREDENTIALS', url:
'https://github.com/ashokitschool/maven-web-app.git'
}
stage('Maven Build'){
def mavenHome = tool name: "Maven-3.9.4", type: "maven"
def mavenPath = "${mavenHome}/bin/mvn"
sh "${mavenPath} clean package"
}
stage('Code Review') {
withSonarQubeEnv('Sonar-Server-7.8') {
def mavenHome = tool name: "Maven-3.9.4", type: "maven"
def mavenCMD = "${mavenHome}/bin/mvn"
sh "${mavenCMD} sonar:sonar"
}
}
stage('Quality Gate') {
steps {
timeout(time: 1, unit: 'HOURS') {
def qg = waitForQualityGate()
if (qg.status != 'OK') {
error "Quality Gate failed: ${qg.status}"
}
}
}
}
stage('Nexus Upload'){
nexusArtifactUploader artifacts: [[artifactId: '01-Maven-Web-App',
classifier: '', file: 'target/01-maven-web-app.war', type: 'war']], credentialsId:
'Nexus-Credentials', groupId: 'in.ashokit', nexusUrl: '3.108.217.159:8081',
nexusVersion: 'nexus3', protocol: 'http', repository: 'ashokit-snapshot-repo',
version: '1.0-SNAPSHOT'
}
stage ('Deploy'){
sshagent(['Tomcat-Server-Agent']) {
sh 'scp -o StrictHostKeyChecking=no target/01-maven-web-app.war ec2-
[email protected]:/home/ec2-user/apache-tomcat-9.0.80/webapps'
}
}
===========================
Pipeline Conditions
===========================
pipeline {
agent any
stages {
stage('Build') {
steps {
// Your build steps here
}
}
stage('SonarQube Analysis') {
steps {
withSonarQubeEnv('YourSonarQubeServer') {
sh 'mvn clean package sonar:sonar'
}
}
}
stage('Quality Gate') {
steps {
timeout(time: 1, unit: 'HOURS') {
def qg = waitForQualityGate()
if (qg.status != 'OK') {
error "Quality Gate failed: ${qg.status}"
}
}
}
}
stage('Deploy') {
when {
expression { currentBuild.resultIsBetterOrEqualTo('SUCCESS') }
}
steps {
// Your deployment steps here
}
}
}
}
################################
Email Notifications In Jenkins
################################
Note: Under Advanced section add your gmail account credential for authentication
purpose.
DL : [email protected]
======================================
Scripted Pipeline Email Notification
=======================================
node {
stage('Demo'){
echo 'Hello world'
}
// send to email
emailext (
subject: "STARTED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'",
body: """<p>STARTED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]':</p>
<p>Check console output at "<a href='${env.BUILD_URL}'>${env.JOB_NAME}
[${env.BUILD_NUMBER}]</a>"</p>""",
to: '[email protected]',
attachLog: true
)
}
==========================================
Declarative Pipeline Email Notification
==========================================
pipeline {
agent any
tools{
maven "Maven-3.9.4"
}
stages {
stage('Clone') {
steps {
git 'https://github.com/ashokitschool/maven-web-app.git'
}
}
stage('Build') {
steps {
sh 'mvn clean package'
}
}
}
post {
failure {
emailext(
subject: "Build Failed: ${currentBuild.fullDisplayName}",
body: "The build ${currentBuild.fullDisplayName} failed.
Please check the console output for more details.",
to: '[email protected]',
from: '[email protected]',
attachLog: true
)
}
success {
emailext(
subject: "Build Successful: $
{currentBuild.fullDisplayName}",
body: "The build ${currentBuild.fullDisplayName} was
successful.",
to: '[email protected]',
from: '[email protected]',
attachLog: true
)
}
}
====================================
Jenkins Job with Parallel Stages
====================================
pipeline {
agent any
stages {
stage('Clone') {
steps {
echo 'Cloning...'
}
}
stage('Build') {
steps {
echo 'Building......'
}
}
stage('Parallel Stage') {
parallel {
stage('Test') {
steps {
echo 'Testing......'
}
}
stage('Code Review') {
steps {
echo 'Running tasks in parallel - code review'
}
}
stage('Nexus Upload') {
steps {
echo 'Running tasks in parallel - nexus upload'
}
}
}
}
stage('Deploy') {
steps {
echo 'Deploying...'
}
}
}
}
===========================================
Working with Shared Libraries in Jenkins
===========================================
=> Create git repo and push shared libraries related groovy files
=> Configure Shared Libraries in Jenkins (Manage Jenkins -> System -> Global
Pipeline Libraries)
@Library('ashokit-shared-lib') _
pipeline {
agent any
stages{
stage('one'){
steps{
welcome( )
}
}
stage('two'){
steps{
script{
calculator.add(10,10)
calculator.add(20,20)
}
}
}
}
}
=======================================
Jenkins Pipeline with Shared Library
=======================================
@Library('ashokit_shared_lib') _
pipeline{
agent any
tools{
maven "Maven-3.9.4"
}
stages{
stage('Git Clone'){
steps{
gitClone('https://github.com/ashokitschool/maven-web-app.git')
}
}
stage('Build'){
steps{
mavenBuild()
}
}
stage('Code Review'){
steps{
sonarQube()
}
}
}
}
=====================
What is Jenkinsfile
=====================
======================================
Jenins Pipeline with try-catch blocks
======================================
pipeline {
agent any
stages {
stage('Build') {
steps {
script {
try {
// Code that might throw an exception
sh 'make -B'
} catch (Exception e) {
// Handle the exception
echo "Build failed: ${e.message}"
currentBuild.result = 'FAILURE'
}
}
}
}
stage('Test') {
steps {
script {
try {
// Code that might throw an exception
sh 'make test'
} catch (Exception e) {
// Handle the exception
echo "Tests failed: ${e.message}"
currentBuild.result = 'FAILURE'
}
}
}
}
}
post {
always {
echo "Always i will execute"
}
success {
echo "Pipeline succeeded!"
}
failure {
echo "Pipeline failed!"
}
}
}
===========================================
What is Multi Branch Pipeline in Jenkins ?
===========================================
=> In realtime, we will have multiple branches in git repo like below
a) main
b) develop
c) feature
d) release
=> We can create one pipeline and we can build the code from multiple branches at a
time using "Multi Branch Pipeline" concept.
=> When we create Multi Branch Pipeline, it will scan all the branches in given git
repo and it will execute pipeline for all branches.
Note: When we run mutli branch pipeline for secondtime, it will verify code changes
happend in which branches and it will execute pipeline for only those branches.
================
Jenkins Summary
================