Search code examples
aws-cloudformationamazon-ecr

How to define an ECR Lifecycle Policy with CloudFormation


In order to limit the number of images in a repository, I'd like to define a Lifecycle policy. Since all the stack is defined with CloudFormation, I'd like to define this policy too.

For example, my policy could be "keep only the most recent 8 images, no matter if tagged or not".


Solution

  • The solution was pretty easy, but since I could not find any example or similar questions (ECR is not mainstream, I know), let me post here the easy solution that I found, which simply requires to insert the policy as JSON into the CloudFormation definition:

    MyRepository:
      Type: AWS::ECR::Repository
      Properties:
        LifecyclePolicy:
          LifecyclePolicyText: |
            {
              "rules": [
              {
                "rulePriority": 1,
                "description": "Only keep 8 images",
                "selection": {
                  "tagStatus": "any",
                  "countType": "imageCountMoreThan",
                  "countNumber": 8
                },
                "action": { "type": "expire" }
              }]
            }
    

    Of course this is very simplistic, but it's the starting point that I was looking for