Rollback to previous version of a docker image in AWS ECR

Goal

I want to have an easy way to revert to a previous version of my app that is deployed as a docker image.

Assumptions

I keep all my Docker images in the AWS Elastic Container Repository. I also tag my images with the current version number (e.g. 20210512-011232-abcde1234 which is a date with time and short commit hash) and additionally, the latest one is tagged as latest.

I got Watchtower running and scanning if there is a new version of the image that it should deploy.

Solution

There are few CLI commands that really help with the job without actually pushing anything through the network.

Get the manifest of an image that you want to become latest:

MANIFEST_TO_BE_LATEST=$(aws ecr batch-get-image --repository-name "yourRepositoryGoesHere" --image-ids imageTag="tagYouWantToBeLatest" --query 'images[].imageManifest' --output text)

Delete current latest tag:

aws ecr batch-delete-image --repository-name "yourRepositoryGoesHere" --image-ids imageTag=latest

Mark the image you want as latest:

aws ecr put-image --repository-name "yourRepositoryGoesHere" --image-tag latest --image-manifest "$MANIFEST_TO_BE_LATEST"