resources/. At runtime, your Pipeline can load and execute these files via libraryResource, decoupling script logic from Groovy and boosting maintainability.
In this guide, we’ll replace hardcoded Trivy commands with a parameterized shell script in resources/scripts/, a Groovy loader helper, and a high-level wrapper. You’ll learn how to:
- Store and version static assets in your shared library
- Dynamically load and execute scripts at Pipeline runtime
- Pass custom arguments from your
Jenkinsfilewithout touching library code
1. The Problem: Hardcoded Commands
Our initialvars/TrivyScan.groovy contained two inline sh blocks with fixed severity levels and exit codes:
Hardcoding severity levels and exit codes makes updates error-prone and requires editing Groovy logic for every change.
2. Solution Overview
We’ll break this into four steps:| Component | Location | Purpose |
|---|---|---|
| Parameterized Script | resources/scripts/trivy.sh | Run trivy image with custom args |
| High-Level Wrapper | vars/TrivyScanScript.groovy | Invoke the script from Groovy with a simple API |
| Generic Loader | vars/loadScript.groovy | Fetch any resources/scripts/* asset at runtime |
| Pipeline Usage | Jenkinsfile | Call TrivyScanScript.vulnerability(...) |
- Add a shell script under
resources/scripts/. - Create a Groovy wrapper (
TrivyScanScript.groovy) that calls the script with parameters. - Build a generic loader (
loadScript.groovy) usinglibraryResource. - Invoke your new API from the
Jenkinsfile.
3. Add the Shell Script Resource
File:resources/scripts/trivy.sh
$1– Docker image (e.g.,my-app:latest)$2– Severity levels (e.g.,LOW,MEDIUM,HIGH)$3– Exit code on vulnerability detection
4. Define the TrivyScanScript Library
File:vars/TrivyScanScript.groovy
Jenkinsfile:
5. Create a Generic Loader: loadScript.groovy
File: vars/loadScript.groovy
This helper lets you load any file under
resources/scripts by passing its filename as config.name.6. How libraryResource Works
libraryResource reads a file from your shared library’s resources directory and returns its content:
- Pass it to an HTTP API
- Write it to disk for local execution
7. Recap
- Static Script (
trivy.sh): Parameterized Trivy invocation - TrivyScanScript: Groovy API that loads & executes the script
- loadScript: Generic loader using
libraryResource
Links and References
- Jenkins Shared Library: https://www.jenkins.io/doc/book/pipeline/shared-libraries/
- Trivy Documentation: https://github.com/aquasecurity/trivy
libraryResourceStep: https://www.jenkins.io/doc/pipeline/steps/workflow-cps/#libraryresource-read-a-resource-from-a-shared-library