🐾Declutter your ECR repository with lifecycle rules 🐾
❓I often see engineers forget about old ECR images, creating images swamp. Sometimes, they create Lambda functions to delete them or even find themselves performing this task manually. Does AWS have a better way to do it?
✅ Of course, AWS developed ECR lifecycle policies for that. You can create several policies and assign evaluation priority to them. Once a lifecycle policy is applied to a repository, images should become expired within 24 hours after they meet the expiration criteria. Test rules can be created to evaluate that only intended images will be expired.
ECR lifecycle policy consists of the following elements:
🔹Tag status
Determines which status image should have to be processed by the policy.
Value: tagged, untagged, or any images.
🔹Tag prefix list
The tagPrefixList parameter is only used if tagStatus is “tagged”. In case you use tags for images that contain specific prefixes, such as dev or prod, you can specify list of such prefixes and apply lifecycle policy only for them.
🔹Count type
You have two options for what you want lifecycle policy to be based on: number of images in repository or number of days image is stored.
Value: imageCountMoreThan or sinceImagePushed.
🔹Count unit
The countUnit parameter is only used if countType is “sinceImagePushed”.
Value: days.
🔹Count number
Indicates the maximum number of images that you want to have in the repository or the maximum number of days to store images.
Value: should be more than 0.
You can find more information on ECR lifecycle policies in the documentation and examples of policies.
🎁 Example of Terraform configuration of ECR policy for deletion of all untagged images except the last one:
resource "aws_ecr_lifecycle_policy" "untagged_policy" {
repository = aws_ecr_repository.repository.name
policy = jsonencode({
"rules" : [
{ "rulePriority" : 1,
"description" : "Keep only last untagged image as backup.",
"selection" : {
"tagStatus" : "untagged",
"countType" : "imageCountMoreThan",
"countNumber" : 1 },
"action" : { "type" : "expire" }
}
]
})
}
If you like this post, you can share APAWS newsletter with friends: