1. Answers
  2. Pruning ECR Images Based on Semantic Versioning Rules

How do I prune images based on semantic versioning rules in ECR?

In this guide, we will create an AWS ECR repository and set up a lifecycle policy that prunes images based on semantic versioning rules. This will help manage the repository by automatically removing old images and retaining only the necessary versions.

The lifecycle policy will be defined to keep only the latest images based on the semantic versioning pattern. For instance, we can keep the latest major.minor versions and remove the rest.

Key Points:

  • Create an ECR repository.
  • Define a lifecycle policy to prune images based on semantic versioning rules.
  • Apply the lifecycle policy to the ECR repository.
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";

// Create an ECR repository
const repository = new aws.ecr.Repository("my-repo", {
    name: "my-repo",
});

// Define a lifecycle policy to prune images based on semantic versioning rules
const lifecyclePolicy = new aws.ecr.LifecyclePolicy("my-repo-lifecycle-policy", {
    repository: repository.name,
    policy: pulumi.interpolate`{
        "rules": [
            {
                "rulePriority": 1,
                "description": "Keep last 5 images with tag prefix 'v'",
                "selection": {
                    "tagStatus": "tagged",
                    "tagPrefixList": ["v"],
                    "countType": "imageCountMoreThan",
                    "countNumber": 5
                },
                "action": {
                    "type": "expire"
                }
            },
            {
                "rulePriority": 2,
                "description": "Keep last 2 images with tag prefix 'v1.' (major.minor)",
                "selection": {
                    "tagStatus": "tagged",
                    "tagPrefixList": ["v1."],
                    "countType": "imageCountMoreThan",
                    "countNumber": 2
                },
                "action": {
                    "type": "expire"
                }
            }
        ]
    }`,
});

// Export the repository URL
export const repositoryUrl = repository.repositoryUrl;

Summary

In this guide, we created an AWS ECR repository and applied a lifecycle policy to prune images based on semantic versioning rules. The policy ensures that only the latest images are retained, helping to manage storage and keep the repository clean.

Deploy this code

Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.

Sign up

New to Pulumi?

Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.

Sign up