Code reuse with Jenkins Shared Libraries

Building pipelines for multiple projects, specially in a distributed architecture such as microservices, is more than normal in nowadays.

One thing that can come up when you are managing multiple pipelines for different projects, is that you might have similar code that needs to run across all jobs. And you don't want to update one by one.

For example, you could have a common function to:

  • create git tags
  • send Slack notifications
  • run a tool to generate a report or scan for vulnerabilities

Jenkins gives the possibility to create a Shared Library that can be imported and reused across multiple jobs to avoid code duplication or silly maintenance.

Here are the steps you need to make use of that in your CI/CD with Jenkins:

  1. create a repository to keep your shared library / common functions (you can use this one as an example)

  2. setup the Shared Library through Jenkins configurations (/configure) image.png

  3. update your Jenkinsfile to make use of it

@Library('jenkins-shared-library') _ // loads all library functions

stage('Demo') {
  common.sayHello("Rodrigo") // references 'common' as library 'common.groovy'
}

Whenever your job is triggered, it will:

  • clone this shared library repo (with most updated code)
  • import the functions
  • run whatever function you call in your pipeline

Conclusions

Easy and straight to the point! Here's the repo: https://github.com/rodrigocprates/jenkins-shared-library