Introduction

In this tutorial, we will look at how to retrieve the latest image in an AWS ECR repository.

ecr describe-images

describe-images command returns the metadata about the images in a repository. The fields returned by this command are listed in the CLI reference doc. We will use the imagePushedAt field to determine the newest images in the repository. The description of the field is as follows:

The date and time, expressed in standard JavaScript date format, at which the current image was pushed to the repository.

Note: the describe-images API is paginated. If you want to disable pagination, use the --no-paginate argument.

How to sort CLI output?

AWS CLI supports client-side filtering using the --query parameter. The --query parameter allows us to filter the output of the command returned by the server. The --query parameter uses JMESPath syntax to create a query expression. The query expression is evaluated against the JSON response returned by the server. The query expression can be used to filter the response, extract specific fields, or perform calculations on the response.

We will use the sort_by method provied by JMESPath to sort the images by the imagePushedAt field. The sort_by method takes two arguments: the list to sort and the field to sort by. The sort_by method returns a list of objects sorted by the specified field. The sort_by method sorts the list in ascending order.

The following command will return the images in the repository sorted by the imagePushedAt field:


aws ecr describe-images --repository-name my-repo --query 'sort_by(imageDetails, &imagePushedAt)'

If you want to sort the images in descending order, you can use the reverse method. The reverse method takes a list as an argument and returns a list with the elements in reverse order. The following command will return the images in the repository sorted by the imagePushedAt field in descending order:


aws ecr describe-images --repository-name my-repo --query 'reverse(sort_by(imageDetails, &imagePushedAt))'

How to retrieve the latest image?

To retrieve the latest image, we can grab the last element from the list returned by the sort_by method. The following command will return the latest image in the repository:


aws ecr describe-images --repository-name my-repo --query 'sort_by(imageDetails, &imagePushedAt)[-1]'

Conclusion

In this tutorial, we looked at how to retrieve the latest image in an AWS ECR repository. We used the describe-images command to retrieve the metadata about the images in the repository. We used the --query parameter to sort the images by the imagePushedAt field.