What is an ECR lifecycle policy and how does ECR storage cost build up?
An ECR lifecycle policy is a deletion tool. It is a set of rules attached to a repository that expires images based on tag status (tagged, untagged, or any), tag patterns, and either image count or time since push. It does not archive or compress anything. Images that match a rule are removed, and storage billing for them stops.
ECR bills storage per GB-month of data stored. Within a repository, a layer is stored once no matter how many images reference it, so a new image adds only its layers that are not already present. Retagging an image moves the tag but leaves the previous image in place as untagged. A CI job that pushes latest or main on every build therefore leaves an untagged image behind on each run, and that image keeps its unique layers billable.
| Source of stored data | Grows with | Freed by a lifecycle rule? |
|---|---|---|
| Untagged images from tag overwrites | Every push of a mutable tag | Yes, with an untagged rule |
| Old uniquely tagged builds | Every CI build | Yes, with a count or age rule |
| Shared base layers | Base image changes | Only when no remaining image references them |
Illustrative estimate (assumed numbers, not a benchmark)
Monthly growth = pushes per day × 30 × average image size × unique-layer share
Assumed inputs: 20 pushes per day, 800 MB per image, 15% unique layers.
Calculation: 20 × 30 × 0.8 GB × 0.15 = 72 GB added per month for one repository.
The same logic limits your savings. Deleting 100 images of 800 MB each does not free 80 GB if most of their layers are shared with images you keep. Base the estimate on unique layers, not on the sum of image sizes.
Who should invest in image cleanup, and when should it be avoided?
Teams that benefit most
Image cleanup pays off where images accumulate faster than anyone notices:
- Busy CI pipelines. A pipeline that pushes an image on every commit or pull request can add hundreds of images a month to a single repository. Most are never deployed.
- Many repositories. With dozens or hundreds of repositories, no one reviews each one by hand. A per-repository policy turns cleanup into a default.
- A growing count of untagged images. Re-pushing a mutable tag such as
latestleaves the previous image untagged. These are usually the safest images to remove and often the quickest win.
When should it be avoided?
Avoid lifecycle policies, or scope them very narrowly, in these situations:
- Small registries with negligible storage cost. If the registry holds a few repositories and the storage line on the bill is a rounding error, a misconfigured rule can delete an image that a running service or a rollback depends on. That outage risk can outweigh years of savings.
- Compliance, audit or forensics requirements. Exclude repositories where you must be able to reproduce exactly what ran at a given time. For these, retention is a requirement, not a cost to optimise.
- Repositories without a consistent tag scheme. Rules can only select by tag and push time. If release, environment and throwaway builds share tag formats, or if deployments rely on mutable tags, no rule can reliably tell them apart. Fix tagging first (see the tag strategy section), then add a policy.
- Repositories referenced mainly by digest. If workloads pin digests and those images are untagged, an untagged-expiry rule can remove images that are in production. Leave these repositories without an untagged rule until every in-use digest also carries a protected tag.
- Long-lived, rarely updated services. A service that deploys once a year can still be running an image that is far older than any reasonable age limit. Age-based rules are a poor fit here. Use a count-based rule with generous headroom, or none.
- When you have no inventory. If you cannot list which images are deployed or kept as rollback targets, you cannot check a preview against anything. Build the inventory before enabling any rule.
A quick way to decide
Compare three numbers:
- Monthly savings = reclaimable unique-layer GB × your storage price per GB-month.
- Effort = engineer hours to inventory, write, preview and roll out rules.
- Risk = what a wrongly deleted image would cost you in outage or recovery time.
Illustrative estimate: if you assume 500 GB reclaimable at $0.10 per GB-month, you save $50 a month. If the rollout takes 20 hours, the payback period is long, and you should first make sure the policy cannot touch images you deploy.
Which images are actually in use? Build the inventory first
Before writing any rule, you need to know what the registry holds and which of those images something still depends on.
- List every repository.
aws ecr describe-repositoriesreturns each repository's name and URI, per region. Run it in every region and account you use, because repositories are regional and easy to forget. - Record image details per repository.
aws ecr describe-imagesreturns digest, tags, size in bytes, push timestamp and, where available, last recorded pull time. From this, note image count, total size, untagged images and the oldest push dates. This shows where the storage actually sits. Often a few CI-heavy repositories account for most of it. - Cross-check against running workloads. Collect image references from ECS task definitions (including older revisions that services or scheduled tasks still use), Kubernetes manifests and Helm values, and Lambda functions packaged as container images.
- Include rollback targets. Whatever your deploy process treats as "previous known good" must survive cleanup, even if nothing currently runs it.
- Watch for digest references. A manifest pinned to a digest can point at an image with no tag, which tag-based reasoning will miss.
A missed reference does not fail at cleanup time. The cached image keeps running containers alive until something has to pull it again. That happens during scale-out, node replacement, a Lambda cold start on a new execution environment, or an emergency rollback. The failure then shows up hours or days later, during an event that is already stressful, and it looks unrelated to the cleanup.
#!/usr/bin/env bash
set -euo pipefail
REGIONS="us-east-1 eu-west-1" # list every region you use; repeat per account
OUT=./ecr-inventory; mkdir -p "$OUT"
for r in $REGIONS; do
# 1. What the registry holds: digest, tags, size, push and last pull time
for repo in $(aws ecr describe-repositories --region "$r" \
--query 'repositories[].repositoryName' --output text); do
aws ecr describe-images --region "$r" --repository-name "$repo" \
--query 'imageDetails[].[imageDigest,join(`,`,imageTags||[`<untagged>`]),imageSizeInBytes,imagePushedAt,lastRecordedPullTime]' \
--output text | sed "s|^|$r\t$repo\t|" >> "$OUT/images.tsv"
done
# 2. ECS: images in ACTIVE task definition revisions, not just the latest
for td in $(aws ecs list-task-definitions --region "$r" --status ACTIVE \
--query 'taskDefinitionArns[]' --output text); do
aws ecs describe-task-definition --region "$r" --task-definition "$td" \
--query 'taskDefinition.containerDefinitions[].image' --output text \
| tr '\t' '\n' >> "$OUT/referenced.txt"
done
# 3. Lambda functions packaged as container images
for fn in $(aws lambda list-functions --region "$r" \
--query "Functions[?PackageType=='Image'].FunctionName" --output text); do
aws lambda get-function --region "$r" --function-name "$fn" \
--query 'Code.ImageUri' --output text >> "$OUT/referenced.txt"
done
done
kubectl get pods -A -o jsonpath='{range .items[*]}{range .spec.initContainers[*]}{.image}{"\n"}{end}{range .spec.containers[*]}{.image}{"\n"}{end}{end}' \
>> "$OUT/referenced.txt"
sort -u "$OUT/referenced.txt" -o "$OUT/referenced.txt"
wc -l "$OUT/images.tsv" "$OUT/referenced.txt"
A bash inventory script that records every ECR image's digest, tags, size, push date and last pull time per region, then collects the image references used by ECS task definitions, Lambda container functions and Kubernetes pods so they can be cross-checked before any lifecycle rule is written.
How does it work? ECR lifecycle policy rule evaluation
In short: you attach a JSON policy to a repository. ECR periodically evaluates every image in that repository against the policy's rules, in priority order. Each image is assigned to the first rule whose tag selection matches it. That rule decides whether the image is kept or marked for expiry, and ECR then deletes the expired images asynchronously. You do not run anything yourself, and nothing outside the repository (clusters, task definitions, functions) is consulted.
Lifecycle rules are evaluated mechanically, and the details of that evaluation decide which image disappears.
Each rule has a rulePriority, a unique integer. Lower numbers are evaluated first. A rule selects images by tagStatus:
taggedrequires atagPrefixListor a wildcardtagPatternList.untaggedmatches images with no tags.anymatches everything. It must carry the highest priority number, so it runs last.
The rule then applies a countType:
imageCountMoreThankeeps the newest N matching images.sinceImagePushedexpires matches older than N days.
Each image is expired by at most one rule. Once an image matches a rule's tag selection, rules with a higher priority number cannot expire it, even if that rule chose to keep it.
Here is how one image moves through a rule set. Assume three rules:
- Priority 1 keeps 30 images tagged
release-*. - Priority 2 expires untagged images after 14 days.
- Priority 3 caps
anyat 300 images.
An image tagged release-2.3 is checked against rule 1 first. If it is among the newest 30 release images, it survives. Because it matched rule 1's tag selection, rules 2 and 3 cannot expire it. This is how a low-priority-number rule protects images from broader rules that run later.
Count-based (imageCountMoreThan) |
Age-based (sinceImagePushed) |
|
|---|---|---|
| Storage growth | Capped and predictable | Unbounded in busy repositories |
| Rarely updated service | Can remove the only known-good fallback | Keeps its recent images, but can expire an old image that is still deployed |
| Bursty CI pushes | A burst can push older images out of the count | Burst images remain until they reach the age limit |
| Best fit | High-churn build repositories | Low-churn services with infrequent releases |
+------------------------------+
| Image arrives for evaluation |
| example tag: release-2.3 |
+--------------+---------------+
|
v
+-----------------------------------+ match +---------------------------+
| Priority 1 tagStatus=tagged |--------->| In newest 30 release-*? |
| tagPrefixList: release- | | yes -> kept |
| imageCountMoreThan 30 | | no -> expired |
+-----------------+-----------------+ | rules 2, 3 never apply |
| no match +---------------------------+
v
+-----------------------------------+ match +---------------------------+
| Priority 2 tagStatus=untagged |--------->| Pushed > 14 days ago? |
| sinceImagePushed 14 days | | yes -> expired |
+-----------------+-----------------+ | no -> kept |
| no match +---------------------------+
v
+-----------------------------------+ match +---------------------------+
| Priority 3 tagStatus=any |--------->| Outside newest 300? |
| imageCountMoreThan 300 | | yes -> expired |
| (highest number, runs last) | | no -> kept |
+-----------------------------------+ +---------------------------+
The first rule whose tag selection matches decides the image's fate;
each image is expired by at most one rule.
An image tagged release-2.3 is checked against rules in ascending rulePriority order. Rule 1's tag selection matches it, so rule 1 alone decides whether it is kept or expired, and rules 2 and 3 never apply to it.
How do you write and preview a safe starting rule set?
A safe first policy has three narrow rules, each scoped to images you have already classified in your inventory. Work through these steps per repository:
- Rule 1 (
rulePriority1): untagged images. SettagStatustountagged,countTypetosinceImagePushed, and expire after a short window such as 7 days. These are usually layers orphaned by retagging. A grace period still protects anything referenced by digest that was pushed recently. - Rule 2 (
rulePriority2): keep the last N releases. SettagStatustotaggedwith atagPrefixListsuch asvorrelease-, and useimageCountMoreThanwith N sized to your rollback depth. Give this rule the higher priority (lower number) than the branch rule. An image that matches a higher-priority rule cannot be expired by a lower-priority one, so releases stay protected even if they also carry a branch tag. - Rule 3 (
rulePriority3): branch and PR builds. Match prefixes such aspr-andfeature-, and expire them after a set age, for example 14 days. - Leave out
tagStatus: anyfor now. Ananyrule matches everything not already claimed, including tags you didn't know existed. Add it only after your inventory shows that nothing important falls through. - Preview before applying. Run
aws ecr start-lifecycle-policy-previewwith--repository-nameand--lifecycle-policy-text. Then pollaws ecr get-lifecycle-policy-previewuntil the status is complete. - Diff the expiry list against your inventory. Compare every expiring digest with the digests that are deployed or pinned. Investigate any overlap. Apply the policy with
put-lifecycle-policyonly when the overlap is zero.
#!/usr/bin/env bash
set -euo pipefail
REPO="payments-api" # placeholder repository name
INVENTORY="deployed-digests.txt" # one sha256:... digest per line (deployed or pinned)
cat > policy.json <<'EOF'
{"rules":[
{"rulePriority":1,"description":"Expire untagged images after 7 days",
"selection":{"tagStatus":"untagged","countType":"sinceImagePushed","countUnit":"days","countNumber":7},
"action":{"type":"expire"}},
{"rulePriority":2,"description":"Keep last 20 v* releases (rollback depth)",
"selection":{"tagStatus":"tagged","tagPrefixList":["v"],"countType":"imageCountMoreThan","countNumber":20},
"action":{"type":"expire"}},
{"rulePriority":3,"description":"Expire PR builds after 14 days",
"selection":{"tagStatus":"tagged","tagPrefixList":["pr-"],"countType":"sinceImagePushed","countUnit":"days","countNumber":14},
"action":{"type":"expire"}},
{"rulePriority":4,"description":"Expire feature branch builds after 14 days",
"selection":{"tagStatus":"tagged","tagPrefixList":["feature-"],"countType":"sinceImagePushed","countUnit":"days","countNumber":14},
"action":{"type":"expire"}}
]}
EOF
aws ecr start-lifecycle-policy-preview --repository-name "$REPO" --lifecycle-policy-text file://policy.json >/dev/null
while true; do
status=$(aws ecr get-lifecycle-policy-preview --repository-name "$REPO" --query status --output text)
[ "$status" != "IN_PROGRESS" ] && break
sleep 5
done
[ "$status" = "COMPLETE" ] || { echo "Preview ended with status $status" >&2; exit 1; }
aws ecr get-lifecycle-policy-preview --repository-name "$REPO" \
--query 'previewResults[].imageDigest' --output text | tr '\t' '\n' | sort -u > expiring.txt
overlap=$(comm -12 expiring.txt <(sort -u "$INVENTORY"))
if [ -n "$overlap" ]; then echo "Policy would expire in-use digests:" >&2; echo "$overlap" >&2; exit 1; fi
aws ecr put-lifecycle-policy --repository-name "$REPO" --lifecycle-policy-text file://policy.json
A starter ECR lifecycle policy with narrow untagged, release and branch rules (no 'any' rule) that is previewed, checked against an inventory of deployed digests, and applied only if no in-use image would expire.
Why does tag strategy decide whether a lifecycle policy is safe?
A lifecycle rule never asks whether an image is running. It only sees tags and push time. If a production task pulls a digest that sits in the expiry set, ECR deletes it anyway. The next scale-out or node replacement then fails to pull. Your tagging scheme is the only signal the rules can read, so it is effectively your safety mechanism.
Give each class of image its own prefix so rules can target it precisely:
| Image class | Example tag | Typical rule | Risk if mixed with other classes |
|---|---|---|---|
| Release | release-2.14.0 |
Keep last N by count, or no expiry | Expired by a broad "any" rule |
| Environment | prod-<sha>, staging-<sha> |
Keep last N per prefix | Rollback target removed |
| Ephemeral build | pr-482-<sha>, ci-<sha> |
Expire after a few days | Accumulates without limit |
Do not deploy by latest or another mutable tag alone. A rule that keeps latest keeps whatever digest the tag points to now. It does not keep the digest your running services pulled last week. Pin deployments to a digest, or to a tag that is never reused.
Turn on tag immutability for repositories that hold release and environment images. When a tag cannot be repushed, a retained tag always refers to the same digest. Without immutability, a push can move the tag and leave the old, still-deployed digest untagged and eligible for expiry.
Be careful with untagged-expiry rules. A tagged multi-arch index references per-platform manifests, and those manifests often appear in the repository as untagged entries. Depending on how your tooling stores signatures, SBOMs and attestations, those artifacts can also appear untagged. A rule that expires everything untagged can remove these entries. Deployment, admission or verification tooling that expects to find them will then fail. Check what your untagged entries actually are before you expire them by age.
How do you roll out and govern policies across many repositories?
Once the rules are proven on a few repositories, stop writing them per repository. Hand-tuned policies drift. One team bumps a count, another adds an exception, and a year later nobody knows which repositories are protected or why. Define a small number of default policies per repository class instead, such as service images, base images and CI scratch repositories, and keep them in the same infrastructure-as-code stack that creates the repositories.
In Terraform, store the policy JSON once as a local value or module input, then attach it with an aws_ecr_lifecycle_policy resource for each repository in a class. CloudFormation and CDK can embed the same text on the repository resource. A change to a default then goes through review once and applies everywhere. Repositories that need different behaviour should declare an explicit override with a comment that explains why.
Don't judge a rollout by what you see right after you apply it. ECR evaluates lifecycle rules asynchronously. Images that match a rule are expired later, not when the policy is saved. AWS documents this delay as up to about 24 hours. Wait at least a day before you conclude a rule is broken.
To confirm the savings, record storage per repository on a schedule. For example, a daily job can sum imageSizeInBytes from aws ecr describe-images. Compare that trend against the registry storage line on your bill. If a repository's size keeps growing after a policy is applied, its tags probably don't match the rules you wrote.
locals {
service_repos = toset(["orders-api", "billing-worker", "web-frontend"])
service_lifecycle_policy = jsonencode({
rules = [
{
rulePriority = 1
description = "Expire untagged images 14 days after push"
selection = {
tagStatus = "untagged"
countType = "sinceImagePushed"
countUnit = "days"
countNumber = 14
}
action = { type = "expire" }
},
{
rulePriority = 2
description = "Keep the 30 most recent release tags (v*)"
selection = {
tagStatus = "tagged"
tagPrefixList = ["v"]
countType = "imageCountMoreThan"
countNumber = 30
}
action = { type = "expire" }
}
]
})
}
resource "aws_ecr_repository" "service" {
for_each = local.service_repos
name = each.key
}
resource "aws_ecr_lifecycle_policy" "service" {
for_each = aws_ecr_repository.service
repository = each.value.name
policy = local.service_lifecycle_policy
}
This Terraform example defines one lifecycle policy for the service-image repository class and attaches it to every repository in that class with for_each, so a single reviewed change applies to all of them.
How can it save engineering time?
The storage savings are often small. The larger benefit is usually the work that stops being necessary.
- No recurring manual cleanup. Without a policy, someone eventually lists images, decides which ones look old and deletes them by hand. Each round needs care, because a wrong digest causes a later pull failure. A policy turns this into a one-time design and review task.
- No custom deletion scripts to own. A homegrown cleanup job needs code, IAM permissions, scheduling, logging and someone to fix it when the API output or tagging changes. A lifecycle policy runs inside ECR with no compute or credentials for you to manage.
- Fewer surprise investigations. Unbounded repositories eventually prompt questions from whoever reviews the bill. Each one means tracing which team owns a repository and what is safe to remove. A default policy per repository class answers that question in advance.
- Cheaper onboarding of new repositories. When the policy is attached in the same infrastructure-as-code module that creates the repository, new services get cleanup without a separate ticket or review.
- Faster audits of retention. With policies in version control, "what do we keep, and why" is answered by reading one file, not by inspecting each repository.
The time savings only hold if the rollout is done carefully. The inventory, preview and diff steps above are what prevent the much larger time cost of debugging a failed scale-out or rollback caused by a deleted image.
Illustrative estimate (assumed numbers, not a benchmark): time saved per year = (manual cleanup hours per round × rounds per year) + (script maintenance hours per year) − (one-time policy rollout hours). With assumed inputs of 4 hours per cleanup round, 6 rounds a year, 10 hours of script maintenance avoided and a 20-hour rollout: (4 × 6) + 10 − 20 = 14 hours saved in the first year, and 34 hours in each year after, as long as the policies need no major changes.
What are the alternatives, and which costs do lifecycle policies not touch?
A lifecycle policy isn't the only way to control registry growth. It is the lowest-maintenance option because ECR evaluates it for you, but it only sees tags, counts and push dates. It cannot tell whether a cluster is still running an image.
| Approach | Protects in-use images | Ongoing effort | Main risk |
|---|---|---|---|
| Lifecycle policy | Only through tag conventions | Low; runs inside ECR | Expiring an old but deployed image |
| Custom cleanup script | Yes; checks live deployments before deleting | High; code, permissions, scheduling | Script bugs or stale inventory |
| Manual periodic deletion | Depends on who runs it | Recurring human time | Gets skipped, or deletes the wrong digest |
| Unlimited retention | Yes, trivially | None | Storage grows indefinitely |
A common hybrid is to let lifecycle rules handle untagged and CI-only images and run a script only for release repositories, where a mistake is expensive.
Lifecycle policies also leave several cost sources untouched:
- Cross-region replication. Each destination region stores and bills its own copy. You need policies in the destination registries too.
- Data transfer and NAT. Pulls from other regions, or through NAT gateways, are billed per GB. Interface VPC endpoints for ECR, plus an S3 gateway endpoint for layer downloads, keep in-region pulls off the NAT path.
- Pull-through cache repositories and OCI artifacts. Cached upstream images, Helm charts and signatures all take up storage and need their own rules.
Illustrative estimate (assumed numbers, not a benchmark): monthly cost = (stored GB × regions × storage price) + (pulled GB via NAT × NAT processing price). With 400 GB × 3 regions × $0.10 = $120, and 3,000 GB × $0.045 = $135, the NAT traffic costs more than all the stored images.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to ecr lifecycle policy, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.