resources directory. By using the libraryResource step in Jenkins pipelines, you can load these files at runtime, write them to the workspace, and execute or parse them as needed.
In this guide, we’ll replace multiple hard-coded Trivy scan invocations with a single parameterized shell script (trivy.sh) stored under resources/scripts. You’ll learn how to load it dynamically from your shared library, keeping your pipeline code DRY and maintainable.
1. The Hardcoded Approach
Here’s a typicalvars/TrivyScan.groovy with duplicated logic for different severities:
2. Extracting a Parameterized Shell Script
Instead of embedding multiple commands in Groovy, create a flexible Bash script that accepts arguments:File Structure
| Path | Description |
|---|---|
resources/scripts/trivy.sh | Parameterized Trivy scan script |
vars/loadScript.groovy | Generic loader for any script in resources |
vars/TrivyScanScript.groovy | Entry point for vulnerability scans |
resources/scripts/trivy.sh
Ensure you commit
trivy.sh with executable permissions (chmod +x trivy.sh). Otherwise, Jenkins won’t be able to run it.3. Creating a Generic Loader: loadScript.groovy
Place the following in vars/loadScript.groovy. This step reads any file from resources/scripts and writes it to the workspace:
libraryResource: Reads the script content as a string.writeFile: Persists it to the workspace.chmod +x: Makes it executable.
4. Wiring It Together: TrivyScanScript.groovy
Use your generic loader and invoke the script with parameters:
config.imageName,config.severity,config.exitCodeare passed from the Jenkinsfile.- Omitting any required key triggers a clear Groovy map-handling error.
You can extend this pattern to other scripts or configuration files without changing your library code.
5. Invoking from a Jenkinsfile
Here’s how to call your new step in a declarative pipeline:6. Summary
- Extract repeated shell logic into
resources/scripts/trivy.sh. - Load it via a generic
loadScriptstep usinglibraryResource. - Invoke it parametrically in your Groovy entrypoint (
TrivyScanScript.groovy). - Customize severity levels, exit codes, and image names without editing library code.