Search code examples
azureazure-container-registryretentionacr

Azure Container Registry retention policy


I have an ACR and it contains docker images for my production and development environments. Since every day there are new images being pushed I'm trying to set a retention policy. My exact use case is as below,

ACR Usage

According to the image, let's say I have 100 images in the ACR and the 100th image is consumed by the development environment. However, the production runs with the 40th image. That being said, I need to keep current and the last 2 images of the production environment as well as the development environment. For example, I need to keep the 38th, 39th, and 40th images as well as 98th, 99th, and 100th images.

I tried using acr purge. Unfortunately, I cannot use either the retention policy or the acr purge for my use case (as per my understandings and maybe I'm wrong).

Can anyone help me with this scenario? Please let me know if you need further information or the requirement is vague!


Solution

  • Please check if the below script using azure CLI command gives an idea to work :

    Which uses Delete by tag method. For this You need to have azure cli installed on your system.

    $registryName = 'registryName'
    $doNotDeleteTags = ''
    $skipLastTags = 3
    
    $repoArray = (az acr repository list --name $registryName --output json | ConvertFrom-Json)
    
    foreach ($repo in $repoArray)
    {
        $tagsArray = (az acr repository show-tags --name $registryName --repository $repo --orderby time_asc --output json | ConvertFrom-Json ) | Select-Object -SkipLast $skipLastTags
    
        foreach($tag in $tagsArray)
        {
    
            if ($donotdeletetags -contains $tag)
            {
                Write-Output ("This tag is not deleted $tag")
            }
            else
            {
                az acr repository delete --name $registryName --image $repo":"$tag --yes
            }
     
        }
    }
    

    Reference: Azure Container Registry - delete all images except 2 - Stack Overflow

    (Or)

    az acr repository show-tags -n MyRegistry --repository MyRepository
     | ConvertFrom-String 
    | %{$_.P2 -replace "[",]",""} 
    | where {$_ -notin "skipthistag","andthistag" } 
    | % {az acr repository delete --name MyRegistry --image MyRepository:$_ --yes}
    

    Reference: How to delete image from Azure Container Registry - Stack Overflow


    References for- Skip last x images:

    1. Cleaning up (ACR) | Andrew Kelleher
    2. powershell script to delete old ACR image - Microsoft Q&A

    Other references:

    1. acr-cleanup:(github.com)
    2. SO reference
    3. (ACR): Tags, Manifests and Cleanup | by Anant Vardhan | Medium