AWS CLI get most recent image tag in ECR
The AWS CLI for ECR is missing something that would be super helpful to have in all sorts of CI/Build/Deployment environments, and that is functionality to retrieve the tag of the most recent image pushed to a repository.
Fortunately, there's a one-liner for that:
$ aws ecr describe-images \
--repository-name ${MY_ECR_REPO} \
--output text \
--query 'sort_by(imageDetails,& imagePushedAt)[*].imageTags[*]' \
| tr '\t' '\n' \
| tail -1
This isn't the most straightforward command, so let's step through it step by step.
First, it finds all images in ECR, and output their tags as text. The sort_by
part of it sorts all images by their push timestamp, ensuring that the most recent image is at the bottom. That can be somewhat messy looking, ending up like this:
947 943
948
952 949 958
959
962 963
974
To clean this up a bit, it uses tr
to replace all \t
(tab) characters with \n
(newlines).
Finally, it uses tail -1
to grab the last entry in the list of tags. As the tags are output by the AWS CLI in order of push, the last entry is guaranteed to point to your most recent image, and now you have a one line command to find the latest tag in an ECR repo!