๐Ÿš€ Automating Image Cleanup in Amazon ECR Using Lifecycle Policies

Alok ShankarAlok Shankar
5 min read

๐ŸŽ‰ Introduction: Say Goodbye to Container Clutter!

If you're using Amazon ECR, chances are your repositories are stuffed with image tags like v1.0-final-final-FINAL, hotfix-now-really, and a dozen variations of latest. Sound familiar?

Just like that overstuffed downloads folder on your desktop, your container registry gets messy fast โ€” especially with CI/CD pipelines pushing fresh builds every hour. Without proper cleanup, this bloats storage, increases costs, and clutters your CI/CD pipelines.

Thatโ€™s where ECR Lifecycle Policies come to the rescue! ๐Ÿฆธโ€โ™‚๏ธ

Thankfully, Amazon ECR lifecycle policies allow you to automate image cleanup by defining rules for retaining or expiring images based on tag status, push time, or tag patterns. These policies act like an auto-cleaning bot for your image repo โ€” sweeping out the old, dusty images and keeping only what you really need (like the latest stable builds or critical hotfixes).

๐Ÿ”ง Why Use ECR Lifecycle Policies?

  • โœ… Reduce storage costs by removing stale images.

  • โœ… Keep repositories clean and manageable.

  • โœ… Automate image retention for CI/CD workflows.

  • โœ… Control cleanup per tag pattern, such as release-, hotfix-, etc.

In this article, i โ€™ll show you how to set up lifecycle rules to:

  • Automatically delete old or untagged images,

  • Retain only your freshest builds,

  • And keep your ECR lean, clean, and ready for deployment.

Letโ€™s container-clean like pros! ๐Ÿ’ช๐Ÿณ

๐Ÿ“Œ Key Concepts of ECR Lifecycle Policies

AttributeDescription
tagStatustagged, untagged, or any โ€” determines which images are selected
tagPrefixListFilters by tag name prefixes
countTypeEither imageCountMoreThan or sinceImagePushed
countNumberNumber of images to retain or age in days
actionCurrently only expire is supported

๐Ÿ› ๏ธ Step-by-Step: Creating Lifecycle Policies with multiple scenarios :

Scenario 1 : โœ… Lifecycle Policy to Keep Only the Most Recent 10 Images (Any Tags)

๐Ÿ”น Step 1: Open ECR Console

Go to: o https://console.aws.amazon.com/ecr/

๐Ÿ”น Step 2: Select Your Repository

Click the repository where you want to apply the policy.

๐Ÿ”น Step 3 :On the Private repositories page, select a repository and that use the Actions drop down to choose Lifecycle policies.

๐Ÿ”น Step 4: On the lifecycle policy rules page for the repository, choose Edit test rules, Create rule

๐Ÿ”น Step 5: Add the Following Rule:

policy in json:

{
  "rules": [
    {
      "rulePriority": 1,
      "description": "Keep only the latest 10 images",
      "selection": {
        "tagStatus": "any",
        "countType": "imageCountMoreThan",
        "countNumber": 10
      },
      "action": {
        "type": "expire"
      }
    }
  ]
}

๐Ÿ”น Step 6: Run test

๐Ÿ”น Step 6: verify the dry run test result

If you feel rule is correct then Apply as lifecycle policy

Post apply life cycle policy - verify life cycle events

๐Ÿ•’ How It Works: Amazon ECR will automatically evaluate this rule periodically and remove older images when there are more than 10 in the repository.

โœ… How AWS Determines "Latest" Images ECR lifecycle policies sort images by push timestamp (i.e., the time they were pushed to the repository). So: โ€ข The "most recently pushed" images are considered the latest. โ€ข The policy:

"countType": "imageCountMoreThan",
"countNumber": 10

๐Ÿ“ŒCan we test policy immediately post apply ?

You cannot force an immediate execution of ECR lifecycle policies โ€” AWS ECR evaluates them periodically in the background, typically within 24 hours, but there's no official SLA or manual trigger.

๐Ÿ” Test Lifecycle Rules: Dry Run

โœ… 1. Use the "Test lifecycle rules" feature (Console):

โ€ข When creating/editing a lifecycle policy in the ECR console, click โ€œTest lifecycle rulesโ€.

โ€ข This shows which images would be deleted if the policy ran now.

โ€ข Itโ€™s a dry run, so no images are actually removed.

๐Ÿท๏ธ Scenario 2: Filtering on image age: Expire images older than 14 days having image tag prefix prod

Policy :

{
  "rules": [
    {
      "action": {
        "type": "expire"
      },
      "selection": {
        "countType": "sinceImagePushed",
        "countUnit": "days",
        "countNumber": 15,
        "tagStatus": "tagged",
        "tagPrefixList": [
          "PROD"
        ]
      },
      "rulePriority": 1
    }
  ]
}

Dry Run result :

๐Ÿท๏ธ Scenario 3: The following example shows the lifecycle policy syntax for a policy that keeps only one untagged image and expires all others.

Life Cycle Policy :

{
  "rules": [
    {
      "action": {
        "type": "expire"
      },
      "selection": {
        "countType": "sinceImagePushed",
        "countUnit": "days",
        "countNumber": 15,
        "tagStatus": "untagged"
      },
      "rulePriority": 1
    }
  ]
}

Dry Run Result :

๐Ÿท๏ธ Scenario 4: Lifecycle Policy with Multiple Tag Prefixes

This example shows how to:

โ€ข Keep only the last 10 images with tag prefix (release-)

โ€ข Keep only the last 5 images with tag prefix (hotfix-)

โ€ข Expire all untagged images

{
  "rules": [
    {
      "rulePriority": 1,
      "description": "Keep last 10 images with tag prefix 'release-'",
      "selection": {
        "tagStatus": "tagged",
        "tagPrefixList": [
          "release-"
        ],
        "countType": "imageCountMoreThan",
        "countNumber": 10
      },
      "action": {
        "type": "expire"
      }
    },
    {
      "rulePriority": 2,
      "description": "Keep last 5 images with tag prefix 'hotfix-'",
      "selection": {
        "tagStatus": "tagged",
        "tagPrefixList": [
          "hotfix-"
        ],
        "countType": "imageCountMoreThan",
        "countNumber": 5
      },
      "action": {
        "type": "expire"
      }
    },
    {
      "rulePriority": 3,
      "description": "Remove all untagged images",
      "selection": {
        "tagStatus": "untagged",
        "countType": "sinceImagePushed",
        "countUnit": "days",
        "countNumber": 1
      },
      "action": {
        "type": "expire"
      }
    }
  ]
}

Dry Run Result :

โœ… Note : In Amazon ECR lifecycle policies, unfortunately, you cannot filter multiple different tag patterns in a single rule using tagPrefixList. The field only accepts a single list of prefixes, and it matches OR logic, not AND.

โœ… How tagPrefixList Works This is allowed:

"tagPrefixList": ["release-", "hotfix-"]

It will match any tag that starts with either release- OR hotfix-. But you cannot use regex or conditions like: โ€ข Contains "v1" and ends with "-stable"

โ€ข Exact matches for arbitrary tag names like "v1.2.3", "prod-latest" together

Policy :

{
  "rules": [
    {
      "rulePriority": 1,
      "description": "Keep last 10 images for tags starting with release- or hotfix-",
      "selection": {
        "tagStatus": "tagged",
        "tagPrefixList": [
          "release-",
          "hotfix-"
        ],
        "countType": "imageCountMoreThan",
        "countNumber": 10
      },
      "action": {
        "type": "expire"
      }
    }
  ]
}

Dry Run Result :

๐Ÿ“ Summary

Amazon ECR lifecycle policies are a simple yet powerful tool to automate image retention, reduce costs, and simplify DevOps workflows. By carefully crafting your policy rules, you can manage your container image repositories with precision and ease.

0
Subscribe to my newsletter

Read articles from Alok Shankar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Alok Shankar
Alok Shankar

Dedicated and highly skilled AWS DevOps and Linux professional with over 10+ years of experience in designing, implementing, and maintaining cloud infrastructure and CICD pipelines. Proficient in optimizing processes, automating workflows, and ensuring the reliability and scalability of cloud-based systems. Demonstrated expertise in Kubernetes and containerization technologies. Proven ability to understand and execute the complete deployment lifecycle. Proven expertise in real-time troubleshooting and leading cross functional teams to success.