π§ LAB GOAL
- Create a Shared Library repository
- Add proper folder structure
- Configure it in Jenkins
- Create an application repo
- Use the library inside Jenkinsfile
- Run the pipeline
By the end, you will understand:
- Who creates it
- Who uses it
- What DevOps controls
- What happens internally
π’ PART 1 β Create Shared Library Repository
Step 1 β Go to GitHub
Click New Repository
Repository name:
company-shared-lib
Click Create.
Step 2 β Create Required Folder Structure
Inside that repository:
Click Add file β Create new file
In the file name field write:
vars/buildApp.groovy
This automatically creates the vars folder.
Step 3 β Write First Shared Function
Inside vars/buildApp.groovy, paste:
def call() {
echo "Shared Library: Starting Build Stage"
sh "echo Running build on $(hostname)"
}
Click Commit.
Step 4 β Add Second Function
Click Add file β Create new file
Name:
vars/deployApp.groovy
Paste:
def call(String environment) {
echo "Shared Library: Deploying to ${environment}"
if (environment == "prod") {
input "Approve Production Deployment?"
}
sh "echo Deployment to ${environment} completed"
}
Click Commit.
β Shared Library Repo Is Ready
Your repo should now look like:
company-shared-lib/
βββ vars/
βββ buildApp.groovy
βββ deployApp.groovy
Important:
-
varsfolder name must be exact - File name becomes function name
-
def call()makes it callable like a function
π’ PART 2 β Configure Shared Library in Jenkins
Now go to your Jenkins UI:
http://13.59.246.183:8080
Step 1 β Go To:
Manage Jenkins
β Manage System
Scroll down to:
Global Trusted Pipeline Libraries
Click Add
(We use Trusted because DevOps owns this library.)
Step 2 β Fill Configuration
Name:
company-lib
Default version:
main
Retrieval Method:
Modern SCM
SCM:
Git
Repository URL:
Paste your shared library GitHub URL
If private:
Add credentials.
Click Save.
β Shared Library Is Now Connected
Jenkins now knows:
"Whenever someone writes @Library('company-lib'), load this repo."
π’ PART 3 β Create Application Repository
Now create second GitHub repository.
Name:
sample-app
Click Create.
Step 1 β Add Jenkinsfile
Inside sample-app:
Add file:
Jenkinsfile
Paste:
@Library('company-lib') _
pipeline {
agent { label 'linux' }
stages {
stage('Build') {
steps {
buildApp()
}
}
stage('Deploy to Dev') {
steps {
deployApp("dev")
}
}
stage('Deploy to Prod') {
steps {
deployApp("prod")
}
}
}
}
Commit.
π’ PART 4 β Create Pipeline Job in Jenkins
Go to Jenkins Dashboard.
Click:
New Item
Name:
sample-app-pipeline
Select:
Pipeline
Click OK.
Step 1 β Configure SCM
Scroll to bottom.
Pipeline section:
Definition:
Pipeline script from SCM
SCM:
Git
Repository URL:
Paste sample-app GitHub URL
Branch:
main
Script Path:
Jenkinsfile
Click Save.
π’ PART 5 β Run The Pipeline
Click:
Build Now
Watch Console Output.
You will see:
- Shared Library loaded
- Build stage executed
- Dev deployment executed
- Production stage waits for approval
Click Approve.
Build completes.
π§ What Just Happened?
Step-by-step internally:
- Jenkins Controller loaded shared library repo
- It imported functions from
vars - It read Jenkinsfile
- It sent shell commands to linux agent
- Agent executed commands
- Controller saved logs
Controller = Brain
Agent = Worker
π§βπ» Who Creates What in Real Company?
| Component | Owner |
|---|---|
| Shared Library Repo | DevOps / Platform Team |
| Jenkins Configuration | DevOps |
| Application Code | Developers |
| Jenkinsfile in App | Usually DevOps template, developers minimal edits |
Developers should NOT control deployment logic.
π What DevOps Must Pay Attention To
Very important production topics:
- Version control shared library
- Protect Git branch
- Use PR approvals
- Never hardcode credentials
- Test library changes in dev Jenkins
- Monitor disk space on agents
- Pin production pipelines to specific library version
Example version pin:
@Library('company-lib@v1.0') _
π¦ Final Architecture
EC2 (Controller):
- Orchestrates
- Stores history
- Loads library
GitHub:
- Shared library repo
- App repo
Agents:
- Execute build
Shared Library solves:
- Duplicate pipeline logic
- Standardization
- Security control
- Production safety
- Centralized CI/CD
π§ LAB GOAL
We will create:
Shared Library function:
buildAndPushECR(imageName, awsRegion)
It will:
- Build Docker image
- Login to ECR
- Tag image
- Push to ECR
βοΈ PRE-REQUISITES (VERY IMPORTANT)
Before starting, make sure:
On Jenkins Linux Agent:
docker --version
aws --version
If not installed:
sudo apt update
sudo apt install docker.io -y
sudo apt install awscli -y
sudo usermod -aG docker jenkins
Restart agent if needed.
π IAM PERMISSION (BEST PRACTICE)
On EC2 Jenkins instance:
Attach IAM Role with permissions:
- AmazonEC2ContainerRegistryFullAccess OR custom policy allowing:
ecr:GetAuthorizationToken
ecr:BatchCheckLayerAvailability
ecr:PutImage
ecr:InitiateLayerUpload
ecr:UploadLayerPart
ecr:CompleteLayerUpload
Best practice: use IAM Role (not access keys).
π’ PART 1 β Create ECR Repository
Go to AWS Console
β ECR
β Create Repository
Name:
demo-app
Click Create.
Copy:
Repository URI
Example:
021399177326.dkr.ecr.us-east-2.amazonaws.com/demo-app
Save this.
π’ PART 2 β Create Shared Library Repo
Go to GitHub β Create new repo:
company-shared-lib
Step 1 β Create Folder
Create:
vars/buildAndPushECR.groovy
Step 2 β Paste This Code
def call(String imageName, String region) {
def accountId = sh(
script: "aws sts get-caller-identity --query Account --output text",
returnStdout: true
).trim()
def ecrRepo = "${accountId}.dkr.ecr.${region}.amazonaws.com/${imageName}"
def tag = "${env.BUILD_NUMBER}"
echo "Building Docker Image..."
sh "docker build -t ${imageName}:${tag} ."
echo "Logging into ECR..."
sh """
aws ecr get-login-password --region ${region} | \
docker login --username AWS --password-stdin ${accountId}.dkr.ecr.${region}.amazonaws.com
"""
echo "Tagging Image..."
sh "docker tag ${imageName}:${tag} ${ecrRepo}:${tag}"
echo "Pushing Image..."
sh "docker push ${ecrRepo}:${tag}"
echo "Image pushed successfully: ${ecrRepo}:${tag}"
}
Commit.
π’ PART 3 β Configure Shared Library in Jenkins
Go to Jenkins:
Manage Jenkins
β Manage System
β Global Trusted Pipeline Libraries
β Add
Fill:
Name:
company-lib
Default Version:
main
SCM: Git
Repository URL: your shared library repo
Save.
π’ PART 4 β Create Application Repo
Create new GitHub repo:
docker-demo-app
Step 1 β Add Dockerfile
Create file:
Dockerfile
Paste:
FROM nginx:alpine
COPY index.html /usr/share/nginx/html/index.html
Step 2 β Add index.html
<h1>Jenkins Shared Library ECR Demo</h1>
Step 3 β Add Jenkinsfile
@Library('company-lib') _
pipeline {
agent { label 'linux' }
environment {
AWS_REGION = "us-east-2"
IMAGE_NAME = "demo-app"
}
stages {
stage('Build and Push to ECR') {
steps {
buildAndPushECR(IMAGE_NAME, AWS_REGION)
}
}
}
}
Commit.
π’ PART 5 β Create Jenkins Pipeline Job
Jenkins β New Item
Name:
docker-ecr-pipeline
Type:
Pipeline
Configure
Pipeline script from SCM
SCM: Git
Repository URL: docker-demo-app repo
Branch: main
Script Path: Jenkinsfile
Save.
βΆοΈ RUN BUILD
Click Build Now.
Watch console.
You should see:
- Docker build
- ECR login
- Image tag
- Docker push
π Verify in AWS
Go to AWS Console β ECR β demo-app
You will see image tag:
1
If build number = 1
π§ What Just Happened?
- Jenkins loaded shared library
- It executed Groovy function
- Agent built Docker image
- Agent authenticated using IAM role
- Agent pushed image to ECR
- Controller saved logs
π’ Real Enterprise Architecture
Platform Team:
- Writes shared library
- Controls Docker logic
- Controls tagging standard
- Controls ECR login method
- Controls security
Developers:
Only write:
buildAndPushECR("my-service", "us-east-2")
They donβt handle login or credentials.
π What DevOps Must Pay Attention To
Very important:
- Never store AWS keys in Jenkinsfile
- Use IAM Role on EC2
- Protect shared library repo
- Version library
- Scan Docker image before push
- Clean old Docker images to save disk
Cleanup example inside library:
sh "docker system prune -f"
π― Interview-Level Explanation
If asked:
βHow do you standardize Docker builds in Jenkins?β
Answer:
"I create a centralized shared library that handles Docker build and ECR push logic using IAM role authentication. This ensures consistent tagging, secure credential handling, and reuse across multiple microservices."
That is senior DevOps answer.
Top comments (0)