Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ismailyenigul/9e60c02a89d83c0c592d711469b30c21 to your computer and use it in GitHub Desktop.
Save ismailyenigul/9e60c02a89d83c0c592d711469b30c21 to your computer and use it in GitHub Desktop.
Sorting AWS ECR images by date with Jenkins groovy script

Updated version of the groovy script at https://kublr.com/blog/advanced-jenkins-groovy-scripting-for-live-fetching-of-docker-images/ to use describe-images to sort AWS ECR images by date.

Don't forget to update MYREPO with your repo name and aws region! Assumption:

  1. Your Jenkins instance has right IAM role to access AWS ECR.
  2. Installed Active Choice Parameter or Extended Choice Parameter Plug-In
  3. Installed awscli on Jenkins instance
import groovy.json.JsonSlurper
def cmd =  ["aws", "ecr", "describe-images", "--region", "eu-west-1",  "--repository-name",  "MYREPO", "--filter", "tagStatus=TAGGED",  "--query", "reverse(sort_by(imageDetails,& imagePushedAt))[*]"]
// Parse JSON into Groovy object
def data = new JsonSlurper().parseText(ecr_images_json.text)
// Prepare the results list
def ecr_images = [];
data.imageTags.each { 
   for (String item : it) {
  	 ecr_images.push(item)
}
} 
// Return the list for Jenkins "select-box"
return ecr_images
@ShubhamRasal
Copy link

ShubhamRasal commented Jun 6, 2022

import groovy.json.JsonSlurperClassic

// Get all images with tags as JSON, the --filter is very important to get only images that have a tag
def cmd = "aws ecr list-images --repository-name MY_IMAGE --filter tagStatus=TAGGED --region us-west-2"
def ecr_images_json = cmd.execute()

// Parse JSON into Groovy object
def data = new JsonSlurperClassic().parseText(ecr_images_json.text)

// Prepare the results list
def ecr_images = [];

// Add all tags
data.imageIds.each { ecr_images.push(it.imageTag) } 

// Return the list for Jenkins "select-box"
return ecr_images

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment