5. How to Use Shared Libraries in Jenkins Pipelines: A Step-by-Step Guide
Table of contents
Introduction
Shared libraries in Jenkins allow you to reuse common functions and steps across multiple pipelines. In this tutorial, we will integrate a Shared Library into our Declarative Pipeline for a Django app. This will simplify the pipeline code and allow for better maintainability and scalability.
We will use the Jenkins-Shared-Libraries repository and implement reusable functions for tasks like code checkout, Docker build, and Docker push.
GitHub Repositories:
Django App Repository: Django-Notes-App
Shared Library Repository: Jenkins-Shared-Libraries
1. Configure Shared Libraries in Jenkins
Step 1: Add Shared Library in Jenkins Configuration
Go to Jenkins Dashboard → Manage Jenkins → Configure System.
Scroll to the Global Pipeline Libraries section.
Click Add under Global Pipeline Libraries.
Name the library (e.g., Shared).
For Source Code Management, select Git and enter the GitHub repository URL for the shared libraries:
https://github.com/imkiran13/Jenkins-Shared-Libraries.git
Save the configuration.
2. Use Shared Library in Pipeline
Now that the shared library is configured, we can use its functions in the Django CI/CD Pipeline.
Updated Pipeline Code Using Shared Library:
@Library("Shared") _
pipeline {
agent { label "jenkins-slave" }
stages {
stage('Checkout') {
steps {
script {
// Using shared library function for Git checkout
code_checkout("https://github.com/imkiran13/Django-Notes-App.git", "main")
}
}
}
stage('Build') {
steps {
script {
// Using shared library function for Docker build
docker_build("notes-app", "latest", "imkiran13")
}
}
}
stage('Push to DockerHub') {
steps {
script {
// Using shared library function for Docker push
docker_push("notes-app", "latest", "imkiran13")
}
}
}
stage('Deploy') {
steps {
echo "Deploying the application"
sh "docker-compose down && docker-compose up -d"
}
}
}
}
Explanation of Pipeline Stages:
Checkout:
Thecode_checkout
function (from the shared library) checks out the Django-Notes-App repository from GitHub.Build:
Thedocker_build
function builds the Docker image for the app.Push to DockerHub:
Thedocker_push
function pushes the Docker image to DockerHub.Deploy:
This stage usesdocker-compose
to deploy the app in a container.
3. Running the Jenkins Slave on Port 8000
After setting up the pipeline, you can run the slave node to deploy the application.
4. Conclusion
By using Shared Libraries, we’ve simplified and modularized the Jenkins pipeline for the Django app. This makes the pipeline more maintainable and reusable across multiple projects.
🚀 Next Steps:
Expand the shared library to include additional functions like testing, notifications, etc.
Explore integrating automated tests in the CI/CD pipeline.
Deploy to cloud platforms (e.g., AWS, Azure, GCP) using Jenkins.
Let me know if you'd like any adjustments! 😊
Feel free to customize the details based on your needs!