How to create a shared library in Jenkins

Updated: February 3, 2024 By: Guest Contributor Post a comment

Introduction

Creating a shared library in Jenkins can be beneficial for automating and streamlining DevOps workflows. Shared libraries in Jenkins allow you to write reusable code that can be shared across multiple Jenkins pipelines. In this tutorial, we will go through the steps of creating a shared library, from basic to advanced examples.

Prerequisites

Before we get started, ensure you have the following:

  • Admin access to a Jenkins instance.
  • Basic understanding of Groovy and Jenkins Pipeline syntax.
  • A version control system (e.g., Git) for storing your shared library code.

Step 1: Creating the Repository

The first step is to create a repository in your version control system to store the shared library code. For this guide, we will use Git:

mkdir my-shared-library
cd my-shared-library
git init

Add your Groovy scripts and resources here.

Step 2: Adding the Shared Library to Jenkins

To add the shared library to Jenkins:

  1. Navigate to Jenkins dashboard.
  2. Go to ‘Manage Jenkins’ > ‘Configure System’.
  3. Scroll down to the ‘Global Pipeline Libraries’ section.
  4. Click the ‘Add’ button.
  5. Fill in the library name and default version (branch).
  6. Specify the source code repository.

Remember to save your changes.

Step 3: Using the Shared Library in Your Pipeline

Let’s create a simple example that uses our shared library. Inside your library repository, create a file named ‘vars/sayHello.groovy’:

def call(name) {
  echo 'Hello, $name!'
}

To use this in your pipeline:

@Library('my-shared-library')_
def callScript = sayHello 'Jenkins User'

This will output ‘Hello, Jenkins User!’ when the pipeline is run.

Advanced Examples

As you become more comfortable with shared libraries, you can implement more complex logic. Here’s an example with a custom class:

package org.myorg

class Helper {
  static void log(String message) {
    echo message
  }
}
var/id/Helper.groovy

In your pipeline script:

@Library('my-shared-library@branch')_
import org.myorg.Helper

Helper.log('Using our helper class.')

This demonstrates how to organize your library into packages and use them in your Jenkins pipelines.

Best Practices

When creating and using Jenkins shared libraries, keep the following best practices in mind:

  • Keep your library code versioned.
  • Write clear, well-documented code.
  • Use unit tests for your Groovy scripts if possible.
  • Refrain from hardcoding sensitive information in the library. Use Jenkins credentials instead.

Conclusion

Creating a Jenkins shared library helps maintain consistency, reduce duplications, and promote reusable code across Jenkins pipelines. By following the outlined steps, you can build a robust shared library system that enhances your CI/CD processes.