0
0
Jenkinsdevops~20 mins

@Library annotation in Jenkins - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the @Library Annotation in Jenkins Pipelines
📖 Scenario: You are working on a Jenkins pipeline project where you want to reuse shared code stored in a separate Git repository. Jenkins provides a way to include shared libraries using the @Library annotation.This project will guide you step-by-step to create a simple Jenkins pipeline script that uses the @Library annotation to load a shared library and call a function from it.
🎯 Goal: Build a Jenkins pipeline script that uses the @Library annotation to load a shared library named my-shared-lib and calls a function sayHello() from that library.
📋 What You'll Learn
Create a Jenkins pipeline script with the @Library annotation
Declare the shared library name exactly as my-shared-lib
Call the sayHello() function from the shared library
Print the output of sayHello() in the pipeline
💡 Why This Matters
🌍 Real World
In real Jenkins projects, shared libraries help teams reuse common pipeline code, reducing duplication and errors.
💼 Career
Understanding how to use the @Library annotation is essential for Jenkins pipeline developers and DevOps engineers to write modular and maintainable pipelines.
Progress0 / 4 steps
1
Create a basic Jenkins pipeline script
Create a Jenkins pipeline script with a pipeline block and a stages section containing one stage named Example. Inside the stage, add a steps block with a placeholder comment.
Jenkins
Need a hint?

Start by writing the basic Jenkins pipeline structure with pipeline, agent any, and one stage named Example.

2
Add the @Library annotation to load the shared library
Add the @Library annotation at the top of the script to load the shared library named my-shared-lib. Use the syntax @Library('my-shared-lib') _ exactly.
Jenkins
Need a hint?

Place the @Library('my-shared-lib') _ annotation at the very top of the Jenkinsfile to load the shared library.

3
Call the sayHello() function from the shared library
Inside the steps block of the Example stage, add a script block. Inside the script block, call the function sayHello() and assign its result to a variable named message.
Jenkins
Need a hint?

Use a script block inside steps to write Groovy code. Call sayHello() and store the result in message.

4
Print the message returned by sayHello()
Still inside the script block, add a println statement to print the message variable.
Jenkins
Need a hint?

Use println(message) to print the message returned by sayHello().