0

I have 8 repositories in my Azure Container Registry. I want to create a Script that delete all images except the last 4 created. I found the following script:

$acrName = 'YourACRName'

$repo = az acr repository list --name $acrName

$repo | Convertfrom-json | Foreach-Object {
    $imageName = $_
    (az acr repository show-tags -n $acrName --repository $_ | 
       convertfrom-json |) Select-Object -SkipLast 4 | Foreach-Object {
           az acr repository delete -n $acrName --image "$imageName:$_"
       }
}

I want to test it in only one repository. How can I select only one?

Patrick Koorevaar
  • 1,219
  • 15
  • 24
exitista
  • 563
  • 2
  • 10
  • 21

2 Answers2

0

If you're okay with using any one, try:

$repo = az acr repository list --name $acrName --top 1

See: https://learn.microsoft.com/en-us/cli/azure/acr/repository?view=azure-cli-latest#az-acr-repository-list

  • I received the following error: Failed At line:9 char:58 + ... az acr repository delete -n $acrName --image "$imageName:$_" + ~~~~~~~~~~~ Variable reference is not valid. ':' was not followed by a valid variable name character. Consider using ${} to delimit the name. – exitista Sep 10 '19 at 14:39
0

You can now use the Azure Cli acr purge command.

The line below will delete all images (--ago 0d) except the last 4 created (--keep 4)

az acr run --cmd "acr purge --filter 'my-image:.*' --ago 0d --untagged --keep 4" --registry mycontainerregistry /dev/null
  • --filter - A repository and a regular expression to filter tags in the repository. Examples: --filter "hello-world:.*" matches all tags in the hello-world repositor, and --filter "hello-world:^1.*" matches tags beginning with 1. Pass multiple --filter parameters to purge multiple repositories.
  • --ago - A Go-style duration string to indicate a duration beyond which images are deleted. The duration consists of a sequence of one or more decimal numbers, each with a unit suffix. Valid time units include "d" for days, "h" for hours, and "m" for minutes. For example, --ago 2d3h6m selects all filtered images last modified more than 2 days, 3 hours, and 6 minutes ago, and --ago 1.5h selects images last modified more than 1.5 hours ago.
  • --untagged - Specifies that manifests that don't have associated tags (untagged manifests) are deleted.
  • --keep - Specifies that the latest x number of to-be-deleted tags are retained.

See also: https://learn.microsoft.com/en-us/azure/container-registry/container-registry-auto-purge

Patrick Koorevaar
  • 1,219
  • 15
  • 24
  • Hi Patrick, Can you please check this question https://stackoverflow.com/questions/71290848/acr-purge-how-can-i-set-regular-expression-to-skip-specific-image-which-starts – Ashish Kumar Feb 28 '22 at 05:27