DEV Community

Alex Aslam
Alex Aslam

Posted on

Jenkins Shared Libraries: Stop Repeating Yourself and Master Complex Pipelines

Hey there, Jenkins wrangler! 👋 Let’s talk about a problem we’ve all faced:

You’ve got 20 Jenkins pipelines across different projects, and each one has the same 100 lines of code to deploy to AWS, send Slack alerts, or run security scans. Every time there’s a tiny change, you’re stuck editing all 20 Jenkinsfiles. Cue the facepalms. 🤦

Enter Jenkins Shared Libraries—your golden ticket to reusable, maintainable, and sane pipelines. Let’s turn you from a Jenkins plumber into a pipeline architect.


What Are Shared Libraries? (Spoiler: They’re Magic)

A Shared Library is a collection of reusable Groovy code you can call from any Jenkins pipeline. Think of it as your personal DevOps toolbox:

  • Functions: Like deployToKubernetes() or sendSlackNotification().
  • Classes: Complex logic wrapped in objects.
  • Global Variables: Constants (e.g., environment URLs) or shortcuts.

No more copying code. Just write once, reuse everywhere.


Why You’ll Love Shared Libraries

  1. DRY Principle: “Don’t Repeat Yourself” becomes reality.
  2. Consistency: All pipelines use the same battle-tested code.
  3. Easier Updates: Fix a bug in one place, not 50 pipelines.
  4. Team Collaboration: Share libraries across projects.

Building Your First Shared Library

Step 1: Create the Library Structure

Your library repo should look like this:

my-shared-library/  
├── vars/                  # Global variables and functions  
│   └── deployAWS.groovy  
├── src/                   # Groovy classes  
│   └── com/example/  
│       └── Logger.groovy  
└── resources/             # Non-code files (JSON, scripts)  
    └── config.json  
Enter fullscreen mode Exit fullscreen mode

Step 2: Write a Reusable Function

Create vars/deployAWS.groovy:

def call(String environment) {  
  // Deploy to AWS using the same steps everywhere  
  sh """  
    aws s3 sync . s3://${environment}-bucket  
    aws cloudfront create-invalidation --paths "/*"  
  """  
  // Send a Slack notification  
  slackSend message: "Deployed to ${environment}!"  
}  
Enter fullscreen mode Exit fullscreen mode

Step 3: Configure Jenkins

  1. Go to Manage Jenkins > Configure System > Global Pipeline Libraries.
  2. Add your library:
    • Name: my-shared-library
    • Default Version: main (or a tag/branch)
    • Repository URL: Your Git URL.

![Jenkins Shared Library config example]


Using the Library in Your Pipeline

Now, any Jenkinsfile can use your shared code:

@Library('my-shared-library') _  // Load the library  

pipeline {  
    agent any  
    stages {  
        stage('Deploy') {  
            steps {  
                deployAWS('production')  // Your custom function!  
            }  
        }  
    }  
}  
Enter fullscreen mode Exit fullscreen mode

Boom. No more rewriting AWS commands in every pipeline.


Level Up: Advanced Use Cases

1. Shared Configuration

Store environment configs in resources/config.json:

{  
  "production": {  
    "bucket": "my-prod-bucket",  
    "slackChannel": "#deploys"  
  }  
}  
Enter fullscreen mode Exit fullscreen mode

Load it in your library:

def loadConfig(String env) {  
  def config = readJSON file: "resources/config.json"  
  return config[env]  
}  
Enter fullscreen mode Exit fullscreen mode

2. Custom Classes

Create src/com/example/Logger.groovy:

package com.example  

class Logger {  
  static void info(String message) {  
    echo "INFO: ${message}"  
  }  

  static void error(String message) {  
    echo "ERROR: ${message}"  
    currentBuild.result = 'FAILURE'  
  }  
}  
Enter fullscreen mode Exit fullscreen mode

Use it in pipelines:

@Library('my-shared-library') _  
import com.example.Logger  

Logger.info("Starting deployment...")  
Enter fullscreen mode Exit fullscreen mode

Best Practices to Avoid Headaches

  1. Version Your Library: Use Git tags to avoid breaking changes.
  2. Test Locally: Use the Jenkins Pipeline Unit Testing Framework.
  3. Document Everything: A README.md saves future-you from rage-quitting.
  4. Limit Permissions: Use @NonCPS for safer Groovy methods.

Common Pitfalls (And How to Dodge Them)

  • “Library Not Found!”: Double-check Jenkins’ library config and repo permissions.
  • Groovy Sandbox Issues: Avoid risky operations (file I/O, network calls) without approval.
  • Overengineering: Start small. Not every script needs to be a library.

Real-World Example: From Chaos to Calm

Meet Team Atlas: They had 15 pipelines, each with 200 lines of duplicate code for SonarQube scans, Docker builds, and Slack alerts. After migrating to Shared Libraries:

  • 500 lines of code reduced to 50.
  • Updates that took hours now take 5 minutes.
  • New engineers onboard faster with standardized steps.

Your Homework

  1. Create a utils Library: Add a sendEmail() function.
  2. Refactor One Pipeline: Replace 10 lines of code with a library call.
  3. High-Five Yourself: You’ve just saved future-you hours of work.

Final Thought: Reuse, Don’t Rebuild

Shared Libraries turn Jenkins from a scripting engine into a scalable DevOps platform. Whether you’re deploying to the cloud, validating PRs, or just tired of copy-pasting, libraries are your new best friend.

Go forth and automate! 🚀

Stuck? Drop a comment below. Let’s build something awesome! 💻✨

AWS Security LIVE! Stream

Streaming live from AWS re:Inforce

What’s next in cybersecurity? Find out live from re:Inforce on Security LIVE!

Learn More

Top comments (0)

Tiugo image

Fast, Lean, and Fully Extensible

CKEditor 5 is built for developers who value flexibility and speed. Pick the features that matter, drop the ones that don’t and enjoy a high-performance WYSIWYG that fits into your workflow

Start now