AWS Builder Center
Stop paying for old container images: ECR lifecycle rules in CDK

Stop paying for old container images: ECR lifecycle rules in CDK

An ECR repository keeps every image you push until a rule removes it. Three lifecycle rules in CDK cap that growth, with the priority and tag rules that trip people up.

Estudiante de ingeniería de software | DevOps
An ECR repository has no expiry on its own. Every image you push stays until something deletes it, and a CI pipeline that pushes on every commit adds up quickly. Each push to a tag that already exists also leaves the previous image behind with no tag at all.
ECR lifecycle policies fix this. You describe which images should go, and ECR removes them. In CDK the policy is a list called  lifecycleRules  on the repository, and the construct turns it into the JSON that ECR expects.

Three rules that cover most repositories

The stack below keeps the five newest images whose tag starts with  release- , drops untagged images after seven days, and puts a ceiling of 30 images on everything else. The numbers are examples. Pick your own.
import * as cdk from 'aws-cdk-lib';
import * as ecr from 'aws-cdk-lib/aws-ecr';

export class RegistryStack extends cdk.Stack {
constructor(scope: cdk.App, id: string) {
super(scope, id);

new ecr.Repository(this, 'AppRepo', {
imageScanOnPush: true,
lifecycleRules: [
{
rulePriority: 1,
description: 'Keep the 5 newest release images',
tagStatus: ecr.TagStatus.TAGGED,
tagPatternList: ['release-*'],
maxImageCount: 5,
},
{
rulePriority: 2,
description: 'Expire untagged images after 7 days',
tagStatus: ecr.TagStatus.UNTAGGED,
maxImageAge: cdk.Duration.days(7),
},
{
rulePriority: 3,
description: 'Keep at most 30 images in total',
tagStatus: ecr.TagStatus.ANY,
maxImageCount: 30,
},
],
});
}
}
I ran  cdk synth  on this stack (as a plain JavaScript version of the same code) and it produced an  AWS::ECR::Repository  with the policy below, embedded as a string in  LifecyclePolicyText . I did not deploy it, so I have not watched ECR actually delete anything.
{
"rules": [
{ "rulePriority": 1,
"selection": { "tagStatus": "tagged", "tagPatternList": ["release-*"],
"countType": "imageCountMoreThan", "countNumber": 5 },
"action": { "type": "expire" } },
{ "rulePriority": 2,
"selection": { "tagStatus": "untagged", "countType": "sinceImagePushed",
"countNumber": 7, "countUnit": "days" },
"action": { "type": "expire" } },
{ "rulePriority": 3,
"selection": { "tagStatus": "any", "countType": "imageCountMoreThan",
"countNumber": 30 },
"action": { "type": "expire" } }
]
}

How the rules interact

Priority decides the order. According to the CDK documentation, lower numbers have higher precedence and the first rule that matches an image is the one applied to it. Priorities must be unique, but they do not need to be sequential. If you leave  rulePriority  out, CDK assigns incrementing priorities to those rules, higher than any rule where you set one yourself.
A rule with  tagStatus  set to  ANY  is special. ECR requires it to have the highest priority number, so it is evaluated last, and the CDK docs add that only one such rule is allowed. That is why the catch-all above is priority 3.
Tagged rules need a tag filter. With  TagStatus.TAGGED  you must pass either  tagPatternList  or  tagPrefixList , and CDK does not allow both in one rule. The ECR documentation calls  tagPatternList  the best practice. It accepts  *  wildcards, with a maximum of four per string. An untagged rule must leave both lists out.
One more detail: when a rule lists several patterns or prefixes, an image has to match all of them to be selected, not just one. A rule with  ['release-*', 'prod-*']  therefore only selects images carrying both tags.

Choosing between count and age

In CDK each rule takes exactly one of  maxImageCount  or  maxImageAge . The count version maps to  imageCountMoreThan  and keeps the newest N images. The age version maps to  sinceImagePushed  and the duration has to be a whole number of days.
Counts suit tags you promote on purpose, such as release tags, because you usually want a fixed number of rollback targets no matter how old they are. Age suits throwaway images like untagged leftovers. Be careful with an age rule on release images: a service that has not been rebuilt for a while would lose the very image it is running from.
ECR also has  sinceImagePulled , which expires images by the time since their last pull. I left it out of the example because I did not run it through CDK.

Things to check before you deploy

Keep enough images for a rollback. If a deployment fails and your orchestrator or your own scripts go back to the previous tag, that image has to still exist. Five release images is a reasonable floor for that, though it is a judgment call and not a rule from AWS.
The repository itself is still retained. In the synthesized template the repository has  DeletionPolicy: Retain , which is the CDK default, so deleting the stack leaves the repository and its images behind. The  emptyOnDelete  property defaults to false, and when it is false the repository must be empty before it can be deleted. Lifecycle rules trim images over time but they do not change either default.
Finally, test a new policy before you trust it. Add rules to a repository that already holds images only after you have checked which images each rule would select, and keep the first version conservative.

Sources

  • Amazon ECR User Guide, lifecycle policy properties
  • AWS CDK API reference: aws-cdk-lib.aws_ecr.LifecycleRule and aws-cdk-lib.aws_ecr.Repository
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article