What is an ECR lifecycle policy and where does registry storage cost come from?

An ECR lifecycle policy is a set of rules attached to a single repository that tells ECR which images to delete automatically, based on tag status, tag prefix, image count or image age. It only deletes. It never moves images to cheaper storage, and it applies only to the repository it is attached to.

Cleanup matters because ECR bills for stored image data per GB-month. A repository that receives a push on every commit keeps growing, because nothing is removed by default. Storage is counted by layer, not by image. Layers shared between images are stored once, and a layer is freed only when no remaining image references it. Deleting an old image whose base layers are still used by newer images frees only the layers unique to that old image.

Illustrative estimate (assumed numbers, not a benchmark)

Assumed inputs:

  • 20 pushes per day
  • 150 MB of new, unique layer data per push
  • A storage price of $0.10 per GB-month, used only for the arithmetic. Check current ECR pricing for your region.

Formulas:

  • Stored GB ≈ pushes per day × unique GB per push × retention days
  • Monthly cost ≈ stored GB × price per GB-month
Retention Stored data Monthly cost
7 days 21 GB ~$2.10
30 days 90 GB ~$9.00
365 days 1,095 GB ~$109.50

Retention length drives the bill almost linearly. However, the savings can be much smaller than the number of deleted images suggests if most of each image is shared base layers.

For small repositories the cost difference may be negligible. In that case the main benefit is operational: a short, readable list of images that are actually deployable.

Where do untagged images come from, and why expire them first?

Every image in ECR is identified by its digest, and a tag is a pointer to one digest. When a pipeline pushes a new build as latest or main, the tag moves to the new digest. The previous image stays in the repository, now with no tags, and it keeps accruing storage. A busy branch that builds on every merge can produce dozens of these orphans a week. Retried CI jobs, pipelines that push a candidate image and then rebuild it, and builds that were overwritten before anyone deployed them all add to the pile.

Because nothing refers to these images by name, expiring them is usually the first and safest rule to add. Use a sinceImagePushed count of a few days. That is short enough to stop the buildup and long enough to cover an in-progress deployment or a rollback that pins the old digest. Any team that pushes mutable tags from CI should start here before touching tagged images. Tagged-image rules need decisions about release retention, and the untagged rule mostly doesn't.

There is one important caveat. A multi-architecture image is an image index that references platform-specific manifests by digest. Those child manifests often carry no tags of their own, so in listings they can look exactly like orphans. If a lifecycle rule removes them, the index tag still exists, but pulls for some or all platforms fail. Preview the policy and check which digests it selects. After the first run, pull each multi-arch tag on every target platform to confirm nothing broke.

How does an ECR lifecycle policy work?

A policy is a JSON document with a rules array. Each rule has a unique integer rulePriority, an optional description, a selection block and an action whose type is expire. The selection block sets three things:

  • tagStatus: tagged, untagged or any. A tagged rule must also have a tagPrefixList (for example release-) or a tagPatternList, which supports * wildcards (for example *-rc*).
  • countType: imageCountMoreThan keeps the newest countNumber images and selects the rest. sinceImagePushed selects images older than countNumber units of countUnit, which is days.

ECR evaluates rules from the lowest rulePriority upward. If an image matches a rule's tag criteria, rules with higher priority numbers cannot expire it, even when the first rule kept it. This is why a tagStatus: any rule must have the highest priority number. Placed earlier, it would claim every image before the more specific rules ran.

Image release-2.3, 60 images in repo → Rule 1 (keep 20 newest release-*): matches, ranked 12th → kept, protected → Rule 2 (untagged, older than 7 days): skipped → Rule 3 (any, keep 50): never applies → survives

If you swap rules 1 and 3, the same image falls outside the newest 50 and is expired. The JSON is identical apart from the order.

sinceImagePushed (age) imageCountMoreThan (count)
Keeps Everything newer than N days The N newest matches
Risk Quiet repository: a service that hasn't shipped in N days can lose its only deployable image Fast churn: a burst of CI pushes can expire last week's running image within hours
Best for Untagged images, feature-branch tags Release tags with a fixed rollback window
               image release-2.3, 60 images in repository
                                    │
                 ┌──────────────────┴──────────────────┐
                 ▼                                     ▼
   AS WRITTEN: release rule first      SWAPPED: any rule first
┌──────────────────────────────────┐  ┌──────────────────────────────────┐
│ P1 tagged release-*  keep 20     │  │ P1 any               keep 50     │
│ match: ranked 12th → KEPT        │  │ match: outside newest 50         │
└────────────────┬─────────────────┘  └────────────────┬─────────────────┘
                 │ claimed                             │ claimed
                 ▼                                     ▼
┌──────────────────────────────────┐  ┌──────────────────────────────────┐
│ P2 untagged  older than 7 days   │  │ P2 untagged  older than 7 days   │
│ skipped: image already claimed   │  │ skipped: image already claimed   │
└────────────────┬─────────────────┘  └────────────────┬─────────────────┘
                 ▼                                     ▼
┌──────────────────────────────────┐  ┌──────────────────────────────────┐
│ P3 any               keep 50     │  │ P3 tagged release-*  keep 20     │
│ never applies to this image      │  │ never applies to this image      │
└────────────────┬─────────────────┘  └────────────────┬─────────────────┘
                 ▼                                     ▼
           ╔═══════════╗                         ╔═══════════╗
           ║ SURVIVES  ║                         ║ EXPIRED   ║
           ╚═══════════╝                         ╚═══════════╝

The same release-2.3 image passes through identical rules in two orders: when the release- rule has the lowest rulePriority the image is claimed and kept, but when the tagStatus any rule runs first it claims the image and expires it.*

How do you write a lifecycle policy for a typical service repository?

The example policy below uses three rules, each scoped to one class of tag. Each rule is designed around two kinds of image that must never be deleted: images currently running in any environment, and images you might roll back to. Every number here is an assumption. Replace each one based on your own deploy frequency and how far back you realistically roll back.

Rule 1: expire untagged images after 7 days

Select tagStatus: untagged and expire with sinceImagePushed at 7 days. Retagging and rebuilds create these orphans, and nothing should deploy by bare digest after a week. If your manifests do pin digests, extend this window or exclude those repositories.

Rule 2: keep the last 30 release images

Select tagStatus: tagged with tagPrefixList: ["v"] and imageCountMoreThan: 30. This rule protects rollback targets. Size N so that it exceeds the number of releases you ship during your longest rollback horizon. For example, if you release daily and might roll back three weeks, 30 leaves margin.

Rule 3: keep the last 10 build images

Match a prefix your CI controls, such as main- or sha-. Raw commit SHAs are a poor fit because a hex string has no stable prefix. Keep the count small, but make sure it covers whatever staging is currently running.

Avoid a catch-all tagStatus: any rule

A final rule with tagStatus: any and a low count is tempting, but it sweeps up everything the earlier rules didn't match. That includes hotfix tags, ad-hoc and manually pushed tags, and signatures or attestations stored as separate entries. Expiring a signature can break admission checks for an image that is still running. It is safer to leave unmatched tags alone and catch them through tag naming conventions.

{
  "rules": [
    {
      "rulePriority": 1,
      "description": "Expire untagged orphans from rebuilds/retags after 7 days (assumed; extend if manifests pin digests)",
      "selection": {
        "tagStatus": "untagged",
        "countType": "sinceImagePushed",
        "countUnit": "days",
        "countNumber": 7
      },
      "action": { "type": "expire" }
    },
    {
      "rulePriority": 2,
      "description": "Protect rollback targets: keep newest 30 release tags (assumed: daily releases, ~3 week rollback horizon)",
      "selection": {
        "tagStatus": "tagged",
        "tagPrefixList": ["v"],
        "countType": "imageCountMoreThan",
        "countNumber": 30
      },
      "action": { "type": "expire" }
    },
    {
      "rulePriority": 3,
      "description": "Keep newest 10 CI build tags (assumed; must cover whatever staging is running)",
      "selection": {
        "tagStatus": "tagged",
        "tagPrefixList": ["main-", "sha-"],
        "countType": "imageCountMoreThan",
        "countNumber": 10
      },
      "action": { "type": "expire" }
    }
  ]
}

A three-rule ECR lifecycle policy that expires untagged images after 7 days, keeps the 30 newest 'v' release tags and the 10 newest CI build tags, and deliberately omits a tagStatus any catch-all rule; every count is an assumed value to replace with your own.

How do you preview and apply a lifecycle policy safely?

Run the policy as a preview before you attach it. aws ecr start-lifecycle-policy-preview takes the repository name and the policy text and evaluates the rules against the images currently in the repository, without deleting anything. The evaluation runs in the background, so poll aws ecr get-lifecycle-policy-preview until its status reports completion. The result lists each image the policy would expire, with its digest, tags, push time and the rule that matched it.

Check that list against two other lists: the images that are deployed now, in every environment, and the images you would need to roll back to. Running workloads usually reference images by tag or digest in manifests, task definitions or Helm values, so pull those references and compare them against the preview. Any running digest in the preview means a rule is too broad. Also check how far back your rollback runbook expects to go. If it assumes the last five releases are available, the policy must keep at least that many.

Once the preview is clean, apply the policy with aws ecr put-lifecycle-policy, then read it back with aws ecr get-lifecycle-policy to confirm the stored text is what you reviewed. Expiration is asynchronous. Images are removed some time after they meet the criteria, so you will not see the effect right away.

Deletion cannot be undone from the registry. The only way to recover an image is to rebuild and repush it. If the base images or dependencies have changed since the original build, the rebuild may not produce the same image. That risk is why you should start conservative and loosen the rules later. Saving a little more storage is not worth losing an image you cannot reproduce.

#!/usr/bin/env bash
set -euo pipefail
REPO="payments-api"          # placeholder repository name
POLICY="file://lifecycle-policy.json"

# 1. Evaluate the policy against current images. Nothing is deleted.
aws ecr start-lifecycle-policy-preview --repository-name "$REPO" --lifecycle-policy-text "$POLICY"

# 2. The preview runs in the background, so poll until it finishes.
while true; do
  status=$(aws ecr get-lifecycle-policy-preview --repository-name "$REPO" --query status --output text)
  [ "$status" = "COMPLETE" ] && break
  [ "$status" = "FAILED" ] && { echo "preview failed" >&2; exit 1; }
  sleep 10
done

# 3. Human-readable list of what would expire, and which rule matched it.
aws ecr get-lifecycle-policy-preview --repository-name "$REPO" --output table \
  --query 'previewResults[].{digest:imageDigest,tags:join(`,`,imageTags || `[]`),pushed:imagePushedAt,rule:appliedRulePriority}'

# 4. Compare against digests that are running or needed for rollback.
#    deployed-digests.txt is built from your manifests/task definitions, one sha256:... per line.
aws ecr get-lifecycle-policy-preview --repository-name "$REPO" \
  --query 'previewResults[].imageDigest' --output text | tr '\t' '\n' | sort -u > would-expire.txt
sort -u deployed-digests.txt > keep.txt
if [ -n "$(comm -12 would-expire.txt keep.txt)" ]; then
  echo "Policy would expire images still in use or needed for rollback:" >&2
  comm -12 would-expire.txt keep.txt >&2
  exit 1   # tighten the rules; do not apply
fi

# 5. Apply only after the preview is clean, then read back the stored text.
aws ecr put-lifecycle-policy --repository-name "$REPO" --lifecycle-policy-text "$POLICY"
aws ecr get-lifecycle-policy --repository-name "$REPO" --query lifecyclePolicyText --output text
# Expiration is asynchronous; matching images are removed some time later, and deletion is permanent.

Previews a lifecycle policy, blocks on any overlap with deployed or rollback digests, then applies the policy and reads back the stored text to confirm it.

When should you avoid aggressive lifecycle rules, and what are the alternatives?

Lifecycle rules see only push dates, tags and image counts. They have no view of what is actually running. When a rule expires an image that a service still uses, nothing fails right away, because running containers already hold the image on their hosts. The failure comes at the next pull. That pull might be triggered by an ECS task rescheduling, a Kubernetes pod moving to a new node, a scale-out event or an autoscaling group replacing instances. A stable service that has not been redeployed in months can be the first to break, often during an incident when you need capacity.

Digest-pinned deployments carry the most risk. If a manifest references repo@sha256:... and the tag that once pointed to that digest has been moved or removed, the image may now be untagged. An untagged-expiry rule will then delete it.

Retention also sets your rollback depth. If you keep only the last five images, you can roll back no further than five builds. If you deploy several times a day, that may cover only hours of history. Storage for a few extra images usually costs far less than an unplanned rebuild.

Approach What it protects Limitation
Conservative count-only rules Keeps a predictable rollback depth Still unaware of what is deployed
Tag immutability for release tags Stops a tag being moved to a different image Does not prevent lifecycle deletion
Protective tag convention (e.g. deployed-) Images whose tags no rule selects Only works if no rule matches those images; confirm in preview
Scripted cleanup using deployment state Anything a cluster or task definition references You must build and maintain the script

How do you roll out and monitor lifecycle policies across many repositories?

Tag conventions and rules need to be designed together. If releases use a pattern like v1.4.2, branch builds use main- or branch-, and pull request builds use pr-, each class can get its own rule and retention count. If tags follow no convention, no rule can be both safe and useful. Enable tag immutability on repositories that hold release tags. Without it, a pipeline that re-pushes v1.4.2 silently moves the tag to a new image, leaves the original as an untagged image, and your untagged-expiry rule then deletes something you believed was a release.

Define the lifecycle policy in infrastructure-as-code in the same module as the repository resource. A repository should not be creatable without one, and a shared module with a default policy that teams can override keeps rule logic in one reviewed place.

Policies are configured per repository and per region. If you use cross-region or cross-account replication, check what exists on the destination repositories. Do not assume the source policy follows the replica. A replica with no policy grows without limit.

Track image count and stored size per repository over time. A steady climb usually means a new tag format is escaping your filters. A sudden drop can mean a broader rule started matching images it shouldn't. Rerun the preview whenever CI changes how it tags images.

Once this is in place, nobody has to run periodic manual cleanup. Because every change goes through review and preview, surprise deletions during a deploy or rollback become much less likely.

#!/usr/bin/env bash
# Audit ECR repos in every region you use, including replication destinations.
# Flags repos with no lifecycle policy or with mutable tags, and prints image
# count and stored bytes so you can trend them over time.
set -euo pipefail

REGIONS="us-east-1 eu-west-1"   # source region plus replica regions

for region in $REGIONS; do
  for repo in $(aws ecr describe-repositories --region "$region" \
      --query 'repositories[].repositoryName' --output text); do

    # Policies are per repository and per region. A replica may have none.
    if ! aws ecr get-lifecycle-policy --region "$region" \
        --repository-name "$repo" >/dev/null 2>&1; then
      echo "WARN $region/$repo: no lifecycle policy"
    fi

    # Mutable release tags can turn re-pushed releases into untagged images.
    mut=$(aws ecr describe-repositories --region "$region" --repository-names "$repo" \
      --query 'repositories[0].imageTagMutability' --output text)
    [ "$mut" = "IMMUTABLE" ] || echo "WARN $region/$repo: tag mutability is $mut"

    # Ship these to your metrics store. A steady climb or a sudden drop is a signal.
    aws ecr describe-images --region "$region" --repository-name "$repo" \
      --query '[length(imageDetails), sum(imageDetails[].imageSizeInBytes)]' \
      --output text | awk -v r="$region/$repo" '{print "METRIC", r, "images="$1, "bytes="$2}'
  done
done

# When CI changes its tag format, preview the IaC-managed policy before applying it.
REPO="payments-api"; REGION="us-east-1"
aws ecr start-lifecycle-policy-preview --region "$REGION" --repository-name "$REPO" \
  --lifecycle-policy-text "file://lifecycle-policy.json" >/dev/null
aws ecr wait lifecycle-policy-preview-complete --region "$REGION" --repository-name "$REPO"
aws ecr get-lifecycle-policy-preview --region "$REGION" --repository-name "$REPO" \
  --query 'previewResults[].{tags:join(`,`, imageTags || `[]`), rule:appliedRulePriority, action:action.type}' \
  --output table

An AWS CLI script that checks each repository in every region for a lifecycle policy and immutable tags, prints image count and stored size for trending, and previews the policy against a repository after CI tag formats change.

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.