Managing Docker images in Amazon Elastic Container Registry (ECR) is a common task for many developers and DevOps practitioners. Often, you need to retrieve the latest versioned tag from a repository to streamline deployment processes or ensure compatibility with the most recent features or fixes.
In this post, we’ll explore a simple Bash command using the AWS CLI and jq
to fetch the latest versioned tag from an ECR repository.
Prerequisites
Before running the command, ensure you have the AWS CLI and jq
installed. You should also have the necessary AWS credentials configured.
Prior to running the ECR describe-images
command, you first need to authenticate to your ECR registry. To do this, execute the following command:
aws ecr get-login-password --region $region | docker login --username AWS --password-stdin $account_id.dkr.ecr.$region.amazonaws.com
Notice that $region
and $account_id
are environment variables that can be set like this:
export region="eu-west-1"
export account_id=123456789012
export repository_name="my-repo-name"
The Command
To get the latest versioned tag from your ECR repository, execute the following command:
aws ecr describe-images --repository-name $repository_name --region $region --query 'sort_by(imageDetails,& imagePushedAt)[*]' --output json | jq 'sort_by(.PushedAt) | .[-1].imageTags[0]'
You can go a step further and get the repo name directly as follows:
latest_tagged_image=$(aws ecr describe-images --repository-name your-repository-name --region $region --query 'sort_by(imageDetails,& imagePushedAt)[*]' --output json | jq 'sort_by(.PushedAt) | .[-1].imageTags[0]')
image_uri="$account_id.dkr.ecr.$region.amazonaws.com/$repository_name:$latest_tagged_image"
echo "Newest image URI: $image_uri"
Explanation
- The
describe-images
command is used to retrieve detailed information about images in the specified ECR repository. - We employ
jq
to process the JSON output. The command first sorts the images by theimagePushedAt
timestamp in ascending order. - The last element (
[-1]
) in the sorted list corresponds to the latest image pushed. - Finally, we extract the versioned tag (
imageTags[0]
) associated with the newest image.