Introduction: Why Scanning and Cleanup Matter

Welcome to the final lesson on Working with Container Registries. Having mastered ECR fundamentals, you will now learn to manage images responsibly through vulnerability scanning and lifecycle policies. Vulnerability scanning analyzes your images against databases of known threats, providing detailed security reports. Lifecycle policies create automated cleanup rules to remove old or unused images, preventing unnecessary storage costs and operational complexity.

In this lesson, you'll achieve two key outcomes: viewing vulnerability scan findings using the aws ecr describe-image-scan-findings command for security analysis, and creating automated cleanup rules using the aws ecr put-lifecycle-policy command with JSON configuration files.

Prerequisites and Context

Before diving in, ensure you have the proper foundation from previous lessons. You should have an existing ECR repository with at least one container image—specifically the my-web-app repository with vulnerability scanning enabled and a Docker image tagged as latest. You can verify your repository and images exist with these commands:

aws ecr describe-repositories --repository-name my-web-app
aws ecr list-images --repository-name my-web-app

For the operations in this lesson, your AWS credentials need additional IAM permissions beyond basic push and pull. The essential permissions are:

  • Vulnerability Scanning:

    • ecr:StartImageScan: Allows you to trigger on-demand vulnerability scans.
    • ecr:DescribeImageScanFindings: Lets you retrieve and view the results of scans.
  • Lifecycle Policy Management:

    • ecr:PutLifecyclePolicy: Allows you to create or update lifecycle policies.
    • ecr:GetLifecyclePolicy: Lets you retrieve existing lifecycle policies.

Most standard ECR policies include these permissions, but if you encounter access denied errors, verify these specific permissions in your IAM policies or roles.

Scanning Images and Interpreting Findings

Amazon ECR provides two scanning approaches: scan-on-push, which automatically scans new images, and on-demand scanning, which lets you manually trigger scans for existing images. While scan-on-push provides immediate feedback, vulnerability databases are constantly updated, making periodic on-demand scans a crucial security practice.

You can trigger an on-demand scan using the aws ecr start-image-scan command, specifying the repository and image tag.

aws ecr start-image-scan \
  --repository-name my-web-app \
  --image-id imageTag=latest

This command queues the scan request and returns immediately. The actual scan runs asynchronously in the background and typically takes a few minutes.

{
    "imageId": {
        "imageDigest": "sha256:8f2a1b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a",
        "imageTag": "latest"
    },
    "imageScanningConfiguration": {
        "scanOnPush": true
    },
    "registryId": "123456789012",
    "repositoryName": "my-web-app"
}

Once the scan is complete, retrieve the findings with the aws ecr describe-image-scan-findings command. This provides a comprehensive security report, including a summary of vulnerabilities by severity.

aws ecr describe-image-scan-findings \
  --repository-name my-web-app \
  --image-id imageTag=latest

The imageScanFindingsSummary section gives a high-level overview, categorizing vulnerabilities by severity. Critical and High severity findings represent the most serious risks and should be addressed immediately. Medium severity issues should be handled in regular maintenance, while Low and Informational findings are less urgent.

{
    "imageScanFindingsSummary": {
        "findingCounts": {
            "CRITICAL": 2,
            "HIGH": 5,
            "MEDIUM": 12,
            "LOW": 8,
            "INFORMATIONAL": 3,
            "UNDEFINED": 0
        }
    },
    ...
}

When triaging findings, focus first on Critical and High severity vulnerabilities. Research each CVE to understand the attack vector and determine if your application is exposed. The most effective remediation is to update base images, upgrade vulnerable packages, and rebuild your container images with the latest security patches.

Policy Design: What to Clean and Why

Lifecycle policies provide automated cleanup mechanisms that prevent ECR repositories from accumulating unlimited numbers of old container images over time. Without proper cleanup strategies, repositories can grow to contain hundreds or thousands of image versions, leading to unnecessary storage costs and operational complexity.

Common cleanup patterns include:

  • Untagged images: Expire after 7-14 days (result from retagging workflows)
  • Tagged versions: Keep recent releases (e.g., 10 most recent) for rollback capability
  • Time-based retention: Balance storage costs against rollback requirements

The key trade-offs involve balancing storage costs against rollback safety and compliance requirements. More aggressive cleanup reduces costs but limits rollback flexibility, while conservative policies provide greater rollback capability at higher storage costs. Start with conservative policies and gradually make them more aggressive as you gain confidence in your operational procedures.

Writing a Lifecycle Policy

Lifecycle policies in Amazon ECR are defined using JSON documents that specify rules for automatically expiring images. Each policy consists of one or more rules that ECR evaluates periodically to determine which images should be removed.

Here's a practical example of a policy that expires untagged images older than 7 days. Save this content to a file named ecr-lifecycle.json.

{
  "rules": [
    {
      "rulePriority": 1,
      "description": "Expire untagged images older than 7 days",
      "selection": {
        "tagStatus": "untagged",
        "countType": "sinceImagePushed",
        "countUnit": "days",
        "countNumber": 7
      },
      "action": { "type": "expire" }
    }
  ]
}

Here is what each of these rules does:

  • rulePriority: Determines evaluation order (lower numbers processed first).
  • selection: Defines which images the rule applies to. tagStatus: "untagged" targets images that lost their tag when a new image was pushed with the same tag name.
  • countType: Specifies how to measure age or quantity. sinceImagePushed measures time from the push date, while imageCountMoreThan measures the number of images.
  • countUnit and countNumber: Define the specific threshold (e.g., days and 7).
  • action: Specifies the action to take. Currently, only "expire" is supported, which permanently deletes matching images. Warning: Expired images cannot be recovered, so test policies carefully.
Applying and Verifying the Policy

Apply your lifecycle policy to a repository using the aws ecr put-lifecycle-policy command, referencing the JSON file you created.

aws ecr put-lifecycle-policy \
  --repository-name my-web-app \
  --lifecycle-policy-text file://ecr-lifecycle.json

The file:// prefix tells the AWS CLI to read the policy from a local file. When successful, ECR returns a confirmation.

{
    "registryId": "123456789012",
    "repositoryName": "my-web-app",
    "lifecyclePolicyText": "{\n  \"rules\": [...]}",
    "lastEvaluatedAt": 1640995200.0
}

After applying the policy, verify it was configured correctly with the aws ecr get-lifecycle-policy command.

aws ecr get-lifecycle-policy --repository-name my-web-app

This command returns the active policy, allowing you to confirm its contents. ECR evaluates lifecycle policies approximately once every 24 hours, so the effects are not immediate. This delay provides a safety buffer against accidental deletion from misconfigured policies. You can monitor the effects by periodically checking your repository's image list with aws ecr list-images.

Pitfalls & Best Practices

To implement scanning and lifecycle policies safely and effectively, avoid these common pitfalls.

  • Use Immutable Tags to Avoid Accidental Deletion: When you push a new image with a tag like latest, the previous image becomes untagged and can be deleted by a cleanup policy. Use immutable tags (like version numbers or Git SHAs) to protect important releases from accidental expiration.
  • Test Policies in Non-Production Environments: Never apply a new lifecycle policy directly to a production repository. An incorrect rule can cause irreversible data loss. Always test policies in a development or staging environment first.
  • Understand Rule Priority: ECR evaluates rules in order of their rulePriority (lowest first) and stops after an image matches its first rule. Design policies with the most specific rules having lower priority numbers to ensure they are evaluated first.
  • Act on Vulnerability Scan Findings: Integrate scanning into your CI/CD pipeline and establish a process to review findings, prioritize remediation based on severity, and rebuild images with security patches.
  • Monitor and Adjust Policies: Regularly monitor your ECR storage costs to confirm your policies are working as expected. If you don't see the expected cost reductions, review your policy rules to ensure they're targeting the right images.

This thoughtful approach ensures your container registry remains secure, cost-effective, and operationally sound.

Lesson Wrap-Up

In this lesson, you mastered advanced ECR management for production environments. You learned to identify security risks by running vulnerability scans with aws ecr start-image-scan and describe-image-scan-findings, and to control costs by creating automated cleanup rules with aws ecr put-lifecycle-policy. These skills transform ECR from a simple image store into a secure, automated component of your software delivery pipeline.

In the upcoming practice, you'll apply these skills by analyzing scan results and creating custom lifecycle policies. The commands and principles are directly transferable to your own projects, provided your local AWS CLI is configured with the necessary IAM permissions for scanning and policy management.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal