How to Call Shared Library Function in Jenkins Pipelines
In Jenkins, you call a shared library function by first loading the library with
@Library annotation or global configuration, then invoking the function directly in your pipeline script using its name. Shared libraries let you reuse code across multiple Jenkinsfiles easily.Syntax
To call a shared library function in Jenkins, you typically use the @Library annotation to load the library, then call the function by its name in your pipeline script.
Example parts:
@Library('libraryName') _: Loads the shared library namedlibraryName.functionName(): Calls the function defined in the shared library.
groovy
@Library('my-shared-lib') _ pipeline { agent any stages { stage('Example') { steps { script { myFunction() } } } } }
Example
This example shows how to call a shared library function named myFunction from a library called my-shared-lib. The function prints a message to the console.
groovy
// vars/myFunction.groovy in shared library def call() { echo 'Hello from shared library function!' } // Jenkinsfile @Library('my-shared-lib') _ pipeline { agent any stages { stage('Call Shared Function') { steps { script { myFunction() } } } } }
Output
[Pipeline] echo
Hello from shared library function!
Common Pitfalls
Common mistakes when calling shared library functions include:
- Not loading the library with
@Libraryor missing global library configuration. - Calling the function with wrong name or missing parentheses.
- Defining the function incorrectly in the shared library (e.g., not using
call()method invars).
Always ensure the shared library is configured in Jenkins and the function is defined properly.
groovy
// Wrong: Missing @Library annotation pipeline { agent any stages { stage('Test') { steps { script { myFunction() // This will fail if library not loaded } } } } } // Right: With @Library annotation @Library('my-shared-lib') _ pipeline { agent any stages { stage('Test') { steps { script { myFunction() } } } } }
Quick Reference
| Step | Description |
|---|---|
| @Library('libName') _ | Load the shared library named 'libName' |
| functionName() | Call the shared library function |
| vars/functionName.groovy | Define function in shared library under 'vars' folder |
| Global Library Config | Add shared library in Jenkins system configuration |
Key Takeaways
Use @Library annotation to load the shared library before calling its functions.
Define shared library functions in the vars folder with a call() method for easy use.
Always configure the shared library globally in Jenkins for smooth access.
Call shared library functions by their name directly in pipeline scripts.
Check for typos and missing parentheses when calling shared library functions.