Shared library in jenkins
Private research annotation
Sign in to add a private research label or note.
- User
Shared library in jenkins
- Assistant
In Jenkins, a "shared library" refers to a set of reusable Groovy scripts that you can share across multiple Jenkins pipeline jobs. It's like a library of custom steps or methods that can be used to define common functionality or logic and avoid duplicating code across different Jenkinsfile or pipeline scripts.
The shared library is defined externally to the jobs themselves, usually in a source code repository (like a Git repository). Once defined, it can be configured in the Jenkins system and then imported into any Jenkins pipeline job to use the functions or classes it defines.
To set up a shared library, you will need to follow these general steps:
-
Write the shared library code: Write Groovy scripts to encapsulate the common functionality you want to provide. These should be structured according to the expected directory structure (see step 2).
-
Organize the shared library structure: Jenkins expects a specific directory structure for shared libraries:
code(root) +- src # Groovy source files | +- org | +- foo | +- Bar.groovy # for org.foo.Bar class | +- vars | +- myStep.groovy # for global 'myStep' variable | +- myStep.txt # help for 'myStep' variable | +- resources # resource files (non-Groovy files) +- org +- foo +- bar.json # static helper data for org.foo.Barsrccontains reusable Groovy code.varscontains global variables that can be called from pipeline scripts.resourcescontains non-Groovy files that can be loaded by the Groovy classes, such as templates or configuration files. -
Host the shared library in a version control system (VCS): Commit your shared library to a VCS like Git so that Jenkins can retrieve it.
-
Configure Jenkins to use the shared library:
- Go to "Manage Jenkins" > "Configure System" in the Jenkins UI.
- Find the "Global Pipeline Libraries" section and add the shared library, specifying the name you'll reference it by, its source code repository location, and which versions to use (branches, tags, etc.).
-
Import the shared library into your Jenkinsfile: In your Jenkins pipeline script (typically
Jenkinsfile), you can then import and use the library with the annotation or by using the step. For example:
-