Sub topic 10
Cleaning up with lifecycle policies
Every image you push to ECR stays there, and you pay for its storage, until something deletes it. CI pipelines that push on every commit can fill a repository with thousands of images in a few months. A lifecycle policy is a set of rules attached to a repository that tells ECR which images to expire automatically.
This chapter assumes you can create a repository and push images with the AWS CLI, and that you know the difference between a tag and a digest from the previous chapters.
What a lifecycle policy is
A lifecycle policy is a JSON document attached to one repository. It contains a list of rules. Each rule selects a set of images and has one action, expire, which deletes the matching images.
Some properties to keep in mind:
- A policy belongs to a single repository. There is no account-wide policy, so repeat it or script it for each repository.
- ECR evaluates policies asynchronously. After an image meets a rule, it can take up to about 24 hours to disappear.
- Expiry is permanent. There is no recycle bin, so a deleted image has to be rebuilt and pushed again.
- Lifecycle policies only expire images. They never change tags, and they never touch other repositories.
Anatomy of a rule
Here is the rule from the earlier example. It expires untagged images 14 days after they were pushed.
{
"rules": [
{
"rulePriority": 1,
"description": "Expire untagged images 14 days after they are pushed",
"selection": {
"tagStatus": "untagged",
"countType": "sinceImagePushed",
"countUnit": "days",
"countNumber": 14
},
"action": {
"type": "expire"
}
}
]
}Apply it with:
aws ecr put-lifecycle-policy \
--repository-name my-app \
--lifecycle-policy-text file://policy.json \
--region us-east-1put-lifecycle-policy replaces the whole policy. It does not merge with the existing one, so always send the complete rule set.
The selection fields
| Field | Meaning |
|---|---|
| `rulePriority` | A unique positive integer. ECR evaluates rules from the lowest number to the highest. |
| `tagStatus` | `tagged`, `untagged`, or `any`. |
| `tagPrefixList` | For `tagged` rules: tag prefixes to match, such as `["dev-"]`. |
| `tagPatternList` | For `tagged` rules: tag patterns that can use `*` wildcards, such as `["*-rc"]`. |
| `countType` | `imageCountMoreThan` or `sinceImagePushed`. |
| `countNumber` | A number of images, or a number of days, depending on `countType`. |
| `countUnit` | `days`. Allowed only with `sinceImagePushed`. |
A tagged rule must include either tagPrefixList or tagPatternList. An image matches a tagged rule if any one of its tags matches.
The two count types
sinceImagePushedmatches images pushed more thancountNumberdays ago. Age is measured from the push time, not from the last pull.imageCountMoreThankeeps the newestcountNumbermatching images and matches everything older. "Newest" is again decided by push time.
Because age is based on push time, a very old image that you pull every day still expires when its rule says so.
How ECR evaluates multiple rules
When a policy has several rules, ECR works through them in priority order. Each image is claimed by the first rule that matches it. Later rules do not see an image that an earlier rule already expired.
One constraint follows from this. A rule with tagStatus set to any matches everything, so it must have the highest priority number in the policy. If an any rule came first, it would claim every image and later rules would never run. ECR rejects a policy where an any rule is not last.
Also, rule priorities do not need to be consecutive. Leave gaps (10, 20, 30) so you can insert a rule later without renumbering.
A realistic multi-rule policy
Suppose my-app receives these kinds of images:
release-*tags that you want to keep for rollbacks.dev-*tags from feature branches that are only useful for a short time.- Untagged images left behind when a mutable tag moved to a newer image.
This policy handles all three:
{
"rules": [
{
"rulePriority": 10,
"description": "Expire untagged images after 14 days",
"selection": {
"tagStatus": "untagged",
"countType": "sinceImagePushed",
"countUnit": "days",
"countNumber": 14
},
"action": { "type": "expire" }
},
{
"rulePriority": 20,
"description": "Keep only the 10 newest dev- images",
"selection": {
"tagStatus": "tagged",
"tagPrefixList": ["dev-"],
"countType": "imageCountMoreThan",
"countNumber": 10
},
"action": { "type": "expire" }
},
{
"rulePriority": 90,
"description": "Safety cap: keep at most 500 images in total",
"selection": {
"tagStatus": "any",
"countType": "imageCountMoreThan",
"countNumber": 500
},
"action": { "type": "expire" }
}
]
}Rule 10 and rule 20 select disjoint sets, so their order does not matter. Rule 90 is the catch-all. By the time it runs, the untagged and extra dev- images are already gone, so it counts only what is left. Release images are never selected by rules 10 or 20, and rule 90 touches them only when the repository passes 500 images.
Preview before you apply
Because expiry cannot be undone, test a policy first. ECR can simulate a policy against the current contents of the repository without deleting anything.
aws ecr start-lifecycle-policy-preview \
--repository-name my-app \
--lifecycle-policy-text file://policy.json \
--region us-east-1
aws ecr get-lifecycle-policy-preview \
--repository-name my-app \
--region us-east-1 \
--query 'previewResults[].{tags:imageTags,pushed:imagePushedAt,rule:appliedRulePriority}'The preview runs asynchronously. If get-lifecycle-policy-preview reports a status of IN_PROGRESS, wait a few seconds and run it again. Each result shows which rule priority would expire the image, which lets you spot a rule that is catching more than you intended.
To check what is currently applied, use aws ecr get-lifecycle-policy --repository-name my-app. To remove the policy entirely, use aws ecr delete-lifecycle-policy --repository-name my-app. Deleting the policy does not restore images that were already expired.
Common mistakes
Expiring images that are still in use
ECR does not know which images your services run. If a rule expires the image behind a running ECS task or EKS pod, nothing breaks right away, because the container already has its layers. The failure appears later, when a new task, a rescheduled pod, or a scale-out event tries to pull the image and gets an "image not found" error.
Assuming age means last use
sinceImagePushed counts from the push time. A base image that you pushed a year ago and still pull daily is old by this measure. Protect long-lived images with a tag convention that your rules do not select, or exclude them by never using a catch-all age rule.
Putting `any` before more specific rules
As described earlier, an any rule must have the highest priority number. Reversing the order makes ECR reject the policy.
Forgetting how immutability changes the shape of the problem
With mutable tags, re-pushing latest leaves the previous image untagged, so an "expire untagged" rule does most of the cleanup. With tag immutability, every push needs a new tag, such as a version or commit SHA. Few images become untagged, and tagged images pile up. In that setup you need tag-based or count-based rules, not just an untagged rule.
Shared layers
Images share layers. Expiring one image removes its layers only if no other image in the repository still references them. The storage you reclaim can therefore be smaller than the size of the expired image.
A practical workflow
- Decide your tag conventions first. Rules are only as precise as your tags.
- Write the policy in a file kept in version control, next to the infrastructure code that creates the repository.
- Run
start-lifecycle-policy-previewand read the results. - Apply it with
put-lifecycle-policy. - Revisit the policy when you change your tagging or release process.
Exercise
A repository holds images tagged release-1.0 through release-1.9 and 300 images tagged ci-<commit>. You want to keep every release image and only the 25 newest ci- images. You also want any remaining images (such as untagged ones) removed after 30 days. Which rules do you write, and in what priority order?
Show answer
Rule 10: tagStatus tagged, tagPrefixList ["ci-"], countType imageCountMoreThan, countNumber 25, action expire. Rule 20 (last, because it uses any): tagStatus any, countType sinceImagePushed, countUnit days, countNumber 30. There is a problem with rule 20, though. Because any matches every remaining image, it also expires release-* images older than 30 days. To keep the releases, make rule 20 untagged instead of any, so it only removes untagged images. Then run the preview to confirm that no release-* image is listed.
Exercise
Why can a lifecycle policy cause a deployment to fail days after it was applied, even though running containers keep working?
Show answer
Running containers already have their image layers on the host. A new task, a rescheduled pod, or a scale-out event must pull the image from ECR again. If a rule expired that image (expiry can take up to about 24 hours to take effect), the pull fails with an "image not found" error.