0
0
Jenkinsdevops~5 mins

@Library annotation in Jenkins - Commands & Configuration

Choose your learning style9 modes available
Introduction
When you want to reuse code in Jenkins pipelines, the @Library annotation helps you load shared libraries easily. It solves the problem of copying the same code in many pipelines by letting you keep common functions in one place.
When you have multiple Jenkins pipelines that need to run similar steps like building or testing.
When you want to keep your pipeline code clean by moving complex logic to shared libraries.
When you want to update common pipeline code in one place and have all pipelines use the new version.
When you want to share pipeline code across different teams or projects in Jenkins.
When you want to use community or custom Jenkins libraries to add extra features to your pipelines.
Commands
This command creates a Jenkinsfile that uses the @Library annotation to load the shared library named 'my-shared-lib' at version 'v1'. The underscore means to import all the library's global vars and steps.
Terminal
echo "@Library('my-shared-lib@v1') _" > Jenkinsfile
Expected OutputExpected
No output (command runs silently)
This command shows the content of the Jenkinsfile to verify the @Library annotation is correctly added.
Terminal
cat Jenkinsfile
Expected OutputExpected
@Library('my-shared-lib@v1') _
This command tests the Jenkinsfile syntax including the @Library annotation to ensure it is valid before running the pipeline.
Terminal
jenkins-jobs --conf jenkins.ini test Jenkinsfile
Expected OutputExpected
INFO:jenkins_jobs.builder:Parsing Jenkinsfile INFO:jenkins_jobs.builder:Validation successful
Key Concept

If you remember nothing else from this pattern, remember: the @Library annotation lets you load shared pipeline code easily to reuse and keep your Jenkins pipelines simple.

Common Mistakes
Forgetting to add the underscore (_) after the @Library annotation
Without the underscore, Jenkins does not import the library's global variables and steps, so your pipeline cannot use them.
Always add an underscore after the @Library annotation like @Library('lib-name@version') _ to import the library correctly.
Using a library name or version that does not exist in Jenkins configuration
Jenkins will fail to load the library and the pipeline will error out because it cannot find the specified library.
Make sure the shared library is configured in Jenkins with the exact name and version you use in the annotation.
Summary
Use the @Library annotation in Jenkinsfiles to load shared pipeline libraries.
Add an underscore (_) after the annotation to import all library steps and variables.
Verify your Jenkinsfile syntax before running pipelines to catch errors early.