0

Delete old ECR images automatically using lifecycle policies – AWS Cloud

When you store container image in ECR (Elastic Container Repository), the image will be kept on there and not deleted automatically. The problem is, your ECR cost will be skyrocket when you have many deploy and it creates a lot of images in ECR.

In order to solve this problem, you can leverage ECR lifecycle policies. This performs to delete old images automatically by using policy you create. The policy has 2 rules:

  • Delete image by Last x days
  • Delete image by Last x images

Let’s try both!

Delete image By Last 30 days

  • Open your ECR dashboard
  • In here, i am using private registry. So open, menu private registry
  • Select your repository name, in the upper right corner click Actions > Lifecycle policies
ECR Lifecycle policies remove old container images automatically
  • Click edit test rules to test your rule first.
  • On Test lifecycle rules page, click Add rule
  • Fill in the following form:
    • Rule priority: 1
    • Rule description: <your description>
    • Images status: Tagged (wildcard matching). FYI, my each image has tag with format: DEV_yyyyddmm_hhiiss (e.g: DEV_20240220_101219)
    • Specify tags for wildcard matching: DEV*
    • Match criteria: Since image pushed: 30 Days
  • Click Save
  • Click Run Test. If you criteria is match, then you will see images on Image matches for test lifecycle rules section
  • Next, click on Apply as lifecycle policy. If a popup appears, just click Apply
  • Now, the policy has been created. Look at Lifecycle events history section, at Message column you see DryRunEvent | 10 images affected. This means the old images are affected and will be deleted in the next day (UTC time).
Delete image on ECR automatically

Delete image By Last 10 images

The step is almost the same as above (Delete image by last 30 days). Just change match criteria field to Image count more than.

  • Select your repository name > Click Lifecycle policies
  • Click create rule
  • Form:
    • Rule priority: 2
    • Rule description: <your description>
    • Images status: Tagged (wildcard matching)
    • Specify tags for wildcard matching: DEV*
    • Match criteria: Image count more than: 10
  • Save
  • The old images will be deleted in the next day

Old Images successfully deleted

To check if old images have successfully deleted, you can see Lifecycle events history, there is PolicyExecutionEvent on Message column, there are 10 images affected (that means 10 images have been deleted from ECR).

delete image on ECR automatically

Ambar Hasbiyatmoko

Hello, I'm web developer. Passionate about programming, web server, and networking.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload the CAPTCHA.