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.
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:
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.
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.
This command queues the scan request and returns immediately. The actual scan runs asynchronously in the background and typically takes a few minutes.
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.
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.
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.
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.
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.
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.sinceImagePushedmeasures time from the push date, whileimageCountMoreThanmeasures the number of images.countUnitandcountNumber: Define the specific threshold (e.g.,daysand7).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.
Apply your lifecycle policy to a repository using the aws ecr put-lifecycle-policy command, referencing the JSON file you created.
The file:// prefix tells the AWS CLI to read the policy from a local file. When successful, ECR returns a confirmation.
After applying the policy, verify it was configured correctly with the aws ecr get-lifecycle-policy command.
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.
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.
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.
