Best Groovy file for Fetching Image from Jfrog Artifactory 2025
Modern software development revolves around continuous integration, continuous deployment, and automation. To keep up, engineers must master tools like Groovy and JFrog Artifactory.
Whether you’re a student starting your DevOps journey, a developer looking to automate your pipelines, or a CI/CD engineer building robust infrastructure, this guide will equip you with the skills to fetch images from JFrog Artifactory using Groovy scripts — with real-world examples and best practices.
Table of Contents
Groovy Script to Fetching Image from JFrog Artifactory – Complete Guide
What is JFrog Artifactory?
JFrog Artifactory is a universal package repository manager that allows teams to store, manage, and retrieve binaries and build artifacts. It supports multiple package types including:
- Maven
- npm
- Docker
- Python (PyPI)
- NuGet
- Helm
Artifactory is widely used in large-scale projects to centralize artifact management. It’s essential when integrating CI/CD pipelines that rely on external resources such as images, logos, configs, and application files.
Why Groovy for Automation?
Groovy is a dynamic scripting language for the Java platform that is used extensively in Jenkins pipelines and automation tools. Here’s why it’s favored:
- Concise syntax (compared to Java)
- Seamless integration with Jenkins
- Supports HTTP and REST APIs easily
- Flexible and readable scripting
Use Case: Downloading Image During Build for PDF or Web UI
Let’s say your pipeline generates documents or deploys a UI that requires an up-to-date company logo or banner image. Instead of committing these assets to your repository every time they change, you can store them in Artifactory and fetch them dynamically using Groovy.
Required Tools and Setup
To implement the Groovy script, you’ll need:
- JFrog Artifactory URL
- Repository name and image path
- Username and API Key (or Access Token)
- Groovy installed locally or in your CI/CD tool (e.g., Jenkins)
- Access permissions for the Artifactory repo
REST API in Artifactory for Downloading Artifacts
Artifactory provides a simple REST API for downloading:
GET https://<artifactory-domain>/artifactory/<repo-path>/<filename>
With Basic Auth, you can authenticate like so:
curl -u user:apikey https://your.artifactory.com/artifactory/images/logo.png --output logo.png
Now let’s translate this into Groovy code.
Groovy Script to Fetch Image from Artifactory
@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7.1')
import groovyx.net.http.RESTClient
import groovyx.net.http.HttpResponseDecorator
import static groovyx.net.http.ContentType.BINARY
def artifactoryBase = "https://your-domain/artifactory"
def repoPath = "/my-repo/images/logo.png"
def username = "your-username"
def apiKey = "your-apikey"
def outputFile = new File("downloaded-logo.png")
def client = new RESTClient(artifactoryBase)
client.auth.basic(username, apiKey)
try {
HttpResponseDecorator response = client.get(
path: repoPath,
contentType: BINARY
)
outputFile.bytes = response.data.bytes
println "✅ Image downloaded successfully to ${outputFile.absolutePath}"
} catch (Exception e) {
println "❌ Failed to download image: ${e.message}"
}
Real-Time Breakdown for Beginners
@Grab
: Automatically downloads required dependencies.RESTClient
: Initializes a REST connection..auth.basic()
: Adds your credentials.response.data.bytes
: Receives image as byte stream.outputFile.bytes
: Writes the image to your local machine.
Avoid Hardcoding Credentials: Use Environment Variables
For production safety:
def username = System.getenv("ARTIFACTORY_USER")
def apiKey = System.getenv("ARTIFACTORY_APIKEY")
In Jenkins, define these as credentials.
Jenkinsfile Pipeline Integration Example
Here’s how to integrate the above logic into a Jenkins pipeline:
pipeline {
agent any
environment {
ARTIFACTORY_USER = credentials('artifactory-user')
ARTIFACTORY_APIKEY = credentials('artifactory-apikey')
}
stages {
stage('Download Image') {
steps {
script {
def url = "https://your-domain/artifactory/my-repo/images/logo.png"
def file = new File("logo.png")
def connection = new URL(url).openConnection()
connection.setRequestProperty("Authorization", "Basic " +
"${ARTIFACTORY_USER}:${ARTIFACTORY_APIKEY}".bytes.encodeBase64().toString())
file.bytes = connection.inputStream.bytes
echo "✅ Logo fetched successfully"
}
}
}
}
}
Fetching Multiple Images Dynamically (Advanced)
If you want to fetch multiple assets in one go:
def imageFiles = ["logo.png", "footer.png", "icon.png"]
imageFiles.each { image ->
def url = "${artifactoryBase}/my-repo/images/${image}"
def file = new File(image)
def conn = new URL(url).openConnection()
conn.setRequestProperty("Authorization", "Basic " +
"${username}:${apiKey}".bytes.encodeBase64().toString())
file.bytes = conn.inputStream.bytes
println "✅ Downloaded: ${image}"
}
Error Handling and Logging
Best practices include handling the following:
try {
def conn = new URL(url).openConnection()
conn.setRequestProperty("Authorization", "Basic " +
"${username}:${apiKey}".bytes.encodeBase64().toString())
def responseCode = conn.responseCode
if (responseCode == 200) {
file.bytes = conn.inputStream.bytes
println "✅ Success"
} else {
println "❌ HTTP ${responseCode}: Failed to download ${url}"
}
} catch (IOException e) {
println "❌ Network error: ${e.message}"
}
Real-World Use Cases in DevOps
- 📁 Configuration Download: Pull YAML, JSON, or INI configs dynamically.
- 🎨 Branding Assets: Always use the latest company logo in builds.
- 📜 Versioned Assets: Fetch images from versioned folders for traceability.
- 📊 Monitoring: Scripts can log image download status for diagnostics.
Securing Your Pipeline
- 🔐 Never expose credentials in your Groovy file.
- 🗝️ Use encrypted secrets via Jenkins or environment variables.
- 🔍 Audit every file you fetch (validate MIME type, checksum, size).
- ✅ Use artifact versioning to avoid overwriting.
For Students: Why This Matters
If you’re a student or beginner:
- You’ll encounter tools like Jenkins and Artifactory in every modern DevOps stack.
- Knowing Groovy helps you customize build pipelines without relying only on YAML.
- Fetching assets dynamically means more flexible, efficient builds.
- You’ll be better prepared for DevOps or SRE job interviews.
Bonus Tip: Validate Image Type After Download
if (!outputFile.name.endsWith(".png")) {
println "⚠️ Warning: This may not be a PNG file."
}
Or use Java’s built-in URLConnection.getContentType()
to verify.
Resources to Explore Further
- 📘 JFrog Artifactory REST API Documentation
- 📗 Groovy HTTPBuilder Documentation
- 📙 Jenkins Pipeline Syntax
- 🎓 Groovy Language Documentation
Summary
With just a few lines of Groovy, you’ve learned how to:
✅ Connect to JFrog Artifactory using REST API
✅ Securely fetch and save image assets
✅ Integrate this into Jenkins for automation
✅ Apply real-world DevOps use cases
✅ Avoid common security and implementation pitfalls
This is a real-world skill every DevOps engineer, student, or backend developer should have in their toolkit. Automating these tasks leads to cleaner pipelines, fewer manual errors, and higher efficiency.