
AWS Cost-Cutters (ECR)
AWS offers scalability and flexibility, but costs can quickly spiral out of control. To manage this, you might be tempted to rely on manual cost optimization; however, you will soon realize that it is time-consuming and error-prone. Automation, on the contrary, becomes essential for efficient cloud cost management.
Today, we will take a look at some lifecycle policies that can be applied to your ECR repositories if your organization uses containers as a deployment unit. The objective is to automatically clean unused or deprecated images in order to keep storage costs under control.
Take a look at the following lifecycle policies:
1. Clean Untagged Images
If the ECR repository is not configured with tag immutability, it is possible to accumulate a large number of untagged images that will likely never be reused. This behavior is typical in development repositories, so applying the following policy helps reduce storage usage and keep the repository clean.
When the rule is matched, the action taken is to expire (delete) the image. The action is taken within 24 hours.
{
"rules": [
{
"rulePriority": 1,
"description": "ECR Clean Untagged",
"selection": {
"tagStatus": "untagged",
"countType": "sinceImagePushed",
"countUnit": "days",
"countNumber": 7
},
"action": {
"type": "expire"
}
}
]
}
Let's look at the selection criteria:
- tagStatus: untagged → The rule applies only to untagged images
- countType: sinceImagePushed → Images are retained for 7 days after being pushed
2. Clean Old tagged Images
A second lifecycle policy is needed to remove old tagged images. This policy should be customized to the release cycle of your team, project, or organization.
Below is an aggressive policy proposal (remember, the goal is to reduce costs):
{
"rules": [
{
"rulePriority": 1,
"description": "ECR Clean Tagged",
"selection": {
"tagStatus": "tagged",
"tagPatternList": ["TAG_PREFIX*"],
"countType": "imageCountMoreThan",
"countNumber": 5
},
"action": {
"type": "expire"
}
},
]
}
This policy expires all tagged images that matches the pattern [TAG_PREFIX]* of the namespace namespace_name while keeping the latest five. For example, if your team releases monthly, this means retaining approximately the last five months of images.
A less aggressive alternative is to move images to the ECR "archive" storage class. However, based on AWS pricing, the cost savings may not be significant enough to justify this approach.

Final Thoughts
Automating cost optimization in AWS enables organizations to reduce expenses, improve efficiency, and maintain better control over their cloud infrastructure.
Two final tips,
- Preview LifeCycle Policies → You can test the preview images in the console before defining
- ECR Replication → remember that if you use ECR replication across regions or accounts, lifecycle policies only apply to repositories within the region where they were created. You will need to replicate the policy across those repositories as well.