pythonimageazure-container-registrydocker-cleanup

Script to delete old images from Azure container registry


I want to remove some unwanted tags/images from various repositories of azure container registry. I want to do all these programmatically. For example, what I need is:

Normally these operations can be done using Azure CLI and az acr commands. Maybe I can create a PowerShell script with az acr commands to accomplish this.

But can I do this with python? Is there something like Graph API to do these operations?

I found this API for ACR but allows to only delete entire registry. It doesn't allow repository-specific operations: https://learn.microsoft.com/en-us/rest/api/containerregistry/

I tried with docker registry API: https://docs.docker.com/registry/spec/api/

#!/bin/bash

export registry="myregistry.azurecr.io"
export user="myusername"
export password="mypassword"

export operation="/v2/_catalog"

export credentials=$(echo -n "$user:$password" | base64 -w 0)

export catalog=$(curl -s -H "Authorization: Basic $credentials" https://$registry$operation)
echo "Catalog"
echo $catalog

But an error is returned all the time:

{"errors":[{"code":"UNAUTHORIZED","message":"authentication required","detail":[{"Type":"registry","Name":"catalog","Action":"*"}]}]}

How can I properly authenticate with ACR before using Docker registry API?


Solution

  • For authenticate to the ACR, you can just use the Basic Authentication method with the user and password. And the format should like this:

    curl -v -u $user:$passwd https://yourACRName.azurecr.io:443/v2/_catalog
    

    For the user and password, I will suggest you use the service principal to authenticate. You can follow the steps in Azure Container Registry authentication with service principals. Take a look at the roles for the ACR. The Contributor role is the appropriate one with enough permission to List all repositories, List all tags of each repository and Remove unwanted images with particular tags. The admin credential is not recommended because of the admin permission.