Best Groovy file for Fetching Image from Jfrog Artifactory 25

Managing dependencies and images in a continuous integration/continuous delivery (CI/CD) pipeline can be challenging. One of the tasks often encountered is Fetching Image from Jfrog Artifactory, especially when dealing with different environments and proxies. In this article, we will walk through how to achieve this using a Groovy script that integrates seamlessly with Jenkins.

Groovy file for Fetching Image from Jfrog Artifactory

Prerequisites

  1. Jenkins Instance: Make sure you have Jenkins installed and running.
  2. Credentials in Jenkins: Ensure you have the necessary credentials stored in Jenkins.
  3. Artifactory Access: Have access to your Artifactory repository.

Step-by-Step Guide

1. Setting Up Jenkins Credentials

First, you need to store your Artifactory credentials in Jenkins. This allows your script to authenticate with Artifactory without hardcoding sensitive information.

  1. Navigate to Jenkins Credentials:
    • Go to Manage Jenkins > Manage Credentials.
  2. Add New Credentials:
    • Click on (global) to open the global credentials domain.
    • Click on Add Credentials.
    • Select Username with password and enter your Artifactory username and password.
    • Give it an ID, for example, artifactory_credentials.

2. Creating the Groovy Script

Here’s a complete Groovy script to fetch image tags from Artifactory, considering proxy settings and authentication.

import groovy.json.JsonSlurper
import com.cloudbees.plugins.credentials.CredentialsProvider
import com.cloudbees.plugins.credentials.common.StandardUsernameCredentials
import jenkins.model.Jenkins
// Retrieve credentials from Jenkins
def creds = CredentialsProvider.lookupCredentials(
    StandardUsernameCredentials.class,
    Jenkins.instance,
    null,
    null
)

def userNm = null
def passWd = null
for (cre in creds) {
    if (cre.id == "artifactory_credentials") {
        userNm = cre.userNm
        passWd = cre.passWd
    }
}

if (userNm == null || passWd == null) {
    println "Credentials not found"
    return []
}
def pxyHost = 'dev-net-proxy.com'
def pxyPort = '8080'
def artifactoryUrl = 'https://artifactory.com/artifactory/api/storage/dkr-public-local/com/api/'

def curlCommand = ["curl", "-s", "-x", "${pxyHost}:${pxyPort}", "-u", "${userNm}:${passWd}", artifactoryUrl]
println("Executing command: ${curlCommand.join(' ')}") // Debug print
try {

    def processCd = curlCommand.execute()
    processCd.waitFor()
    
    if (processCd.exitValue() != 0) {
      
        println processCd.errorStream.text
        
    }
    
    def reSpn = processCd.text
    println "Response:"
    println reSpn
   
    def jsonReSp = new JsonSlurper().parseText(reSpn)
    println "Parsed JSON:"
    println jsonReSp 
    
    def regexp = /\/(\d+\.\d+\.\d+(-[A-Za-z]+)?)$/
    

    def tags = jsonReSp.children.findResults { 
     
        def maTcrUr = (it.uri =~ regexp)
        if (maTcrUr) {
            return maTcrUr[0][1]
        }
        
    }
    println "Filtered Tags:"
    println tags 
    return tags
} catch (Exception e) {
    
    println "Exception occurred: ${e.message}"
    e.printStackTrace()
    return [] 
}

3. Adding the Script to Jenkins

To integrate this script into Jenkins, follow these steps:

  1. Go to Jenkins Job Configuration:
    • Open the job where you want to add this functionality.
    • Scroll down to the Build Environment section.
  2. Add Active Choice Parameter:
    • Press on Parameter and choose Active Choices Parameter.
    • Configure the parameter with a suitable name (e.g., ImageTags).
  3. Add Groovy Script:
    • In the Groovy Script section of the parameter, paste the Groovy script provided above.
  4. Save the Job Configuration:
    • Click Save to apply the changes.

4. Explanation of the Script

  • Import Statements: The script imports necessary classes for JSON parsing and Jenkins credentials handling.
  • Credentials Retrieval: It fetches the credentials stored in Jenkins with the ID artifactory_credentials.
  • Proxy and URL Setup: The script defines the proxy settings and Artifactory URL.
  • Curl Command Construction: Constructs the curl command with the necessary parameters, including proxy settings and authentication.
  • Executing Curl Command: Executes the command and captures the response.
  • Response Parsing: Parses the JSON response to extract image tags using a regular expression.
  • Exception Handling: Handles any exceptions that might occur during the execution.

How to resolve failed to pull Helm chart

Conclusion

By following the steps outlined in this article, you can effectively fetch image tags from Artifactory using a Groovy script in Jenkins. This approach ensures that your credentials are securely managed and that your script handles proxies and authentication seamlessly. Integrating this script into your Jenkins jobs will help streamline your CI/CD pipelines and manage your dependencies more efficiently.

Leave a Comment