How to delete image from Azure Container Registry - azure

Is there a way to delete specific tags only? I only found a way to delete the whole registry using the REST/cli-acr
Thanks

UPDATE COPIED FROM BELOW:
As an update, today we've released a preview of several features including repository delete, Individual Azure Active Directory Logins and Webhooks.
Original answer:
We are hardening up the registry for our GA release later this month. We've deferred all new features while we focus on performance, reliability and additional azure data centers, delivering ACR across all public data centers by GA.
We will provide deleting of images and tags in a future release.
We're started to use https://github.com/Azure/acr/ to track features and bugs.
Delete is captured here: https://github.com/Azure/acr/issues/33
Thanks for the feedback,
Steve

You can use Azure CLI 2.0 to delete images from a repository with a given tag:
az acr repository delete -n MyRegistry --repository MyRepository --tag MyTag
MyRegistry is the name of your Azure Container Registry
MyRepository is the name of the repository
MyTag denotes the tag you want to delete.
You can also choose to delete the whole repository by omitting --tag MyTag. More information about the az acr repository delete command can be found here: https://learn.microsoft.com/en-us/cli/azure/acr/repository#delete

Here is a powershell script that deletes all Azure Container Registry tags except for tags MyTag1 and MyTag2:
az acr repository show-tags -n MyRegistry --repository MyRepository | ConvertFrom-String | %{$_.P2 -replace "[`",]",""} | where {$_ -notin "MyTag1","MyTag2" } | % {az acr repository delete -n MyRegistry --repository MyRepository --tag $_ --yes}
It uses Azure CLI 2.0.

I had a similar problem where I wanted to remove historical images from the repository as our quota had reached 100%
I was able to do this by using the following commands in the Azure CLI 2.0. The process does the following : obtain a list of tags, filter it with grep and clean it up with sed before passing it to the delete command.
Get all the tags for the given repository
az acr repository show-tags -n [registry] --repository [repository]
Get all the tags that start with the specific input and pipe that to sed which will remove the trailing comma
grep \"[starts with] | sed 's/,*$//g'
Using xargs, assign the output to the variable X and use that as the tag.
--manifest :
Delete the manifest referenced by a tag. This also deletes any associated layer data and all other tags referencing the manifest.
--yes -y : Do not prompt for confirmation.
xargs -I X az acr repository delete -n [registry] --repository [repository] --tag X --manifest --yes
e.g. registry = myRegistry, repository = myRepo, I want to remove all tags that start with the tagname 'test' ( this would include test123, testing etc )
az acr repository show-tags -n myRegistry --repository myRepo | grep \"test | sed 's/,*$//g' | xargs -I X az acr repository delete -n myRegistry --repository myRepo --tag X --manifest --yes
More information can be found here Microsoft Azure Docs

Following answer from #christianliebel Azure CLI generates error unrecognized arguments: --tag MyTag:
➜ az acr repository delete -n MyRegistry --repository MyRepository --tag MyTag
az: error: unrecognized arguments: --tag MyTag
I was using:
➜ az --version
azure-cli 2.11.1
This works:
➜ az acr repository delete --name MyRegistry --image Myrepository:Mytag
This operation will delete the manifest 'sha256:c88ac1f98fce390f5ae6c56b1d749721d9a51a5eb4396fbc25f11561817ed1b8' and all the following images: 'Myrepository:Mytag'.
Are you sure you want to continue? (y/n): y
➜
Microsoft Azure CLI docs example:
https://learn.microsoft.com/en-us/cli/azure/acr/repository?view=azure-cli-latest#az-acr-repository-delete-examples

As an update, today we've released a preview of several features including repository delete, Individual Azure Active Directory Logins and Webhooks.
Steve

Following command helps while deleting specific images following a name or search pattern :-
az acr repository show-manifests -n myRegistryName --repository myRepositoryName --query '[].tags[0]' -o yaml | grep 'mySearchPattern' | sed 's/- /az acr repository delete --name myRegistryName --yes --image myRepositoryName:/g'
My use case was to delete all Container Registeries which were created before August in 2020 so I copied the output of the following command and then executed them, as my manifest names had creation Date like DDMMYYYY-HHMM:-
az acr repository show-manifests -n myRegistryName --repository myRepositoryName --query '[].tags[0]' -o yaml | grep '[0-7]2020-' | sed 's/- /az acr repository delete --name myRegistryName --yes --image myRepositoryName:/g'
Reference: Microsoft ACR CLI

I have used the REST Api to delete the empty tagged images from a particular repository, documentation available here
import os
import sys
import yaml
import json
import requests
config = yaml.safe_load(
open(os.path.join(sys.path[0], "acr-config.yml"), 'r'))
"""
Sample yaml file
acr_url: "https://youregistryname.azurecr.io"
acr_user_name: "acr_user_name_from_portal"
acr_password: "acr_password_from_azure_portal"
# Remove the repo name so that it will clean all the repos
repo_to_cleanup: some_repo
"""
acr_url = config.get('acr_url')
acr_user_name = config.get("acr_user_name")
acr_password = config.get("acr_password")
repo_to_cleanup = config.get("repo_to_cleanup")
def iterate_images(repo1, manifests):
for manifest in manifests:
try:
tag = manifest['tags'][0] if 'tags' in manifest.keys() else ''
digest = manifest['digest']
if tag is None or tag == '':
delete = requests.delete(f"{acr_url}/v2/{repo1}/manifests/{digest}", auth=(acr_user_name, acr_password))
print(f"deleted the Tag = {tag} , Digest= {digest}, Status {str(delete)} from Repo {repo1}")
except Exception as ex:
print(ex)
if __name__ == '__main__':
result = requests.get(f"{acr_url}/acr/v1/_catalog", auth=(acr_user_name, acr_password))
repositories = json.loads(result.content)
for repo in repositories['repositories']:
if repo_to_cleanup is None or repo == repo_to_cleanup:
manifests_binary = requests.get(f"{acr_url}/acr/v1/{repo}/_manifests", auth=(acr_user_name, acr_password))
manifests_json = json.loads(manifests_binary.content)
iterate_images(repo, manifests_json['manifests'])

I tried all commands but none worked.I though that it could be stacked so I went to my portal azure and deleted my repository by myself. It works

Related

Azure Purge Command not deleting images

I'm trying to delete TAGGED images in ACR using the below command. But it says 0 deleted images. There are around 100+ images older than 90 days.
Number of deleted tags: 0
$REGISTRY = "MYREGISTRY"
$PURGE_CMD = "acr purge --filter 'MYREPO:.*' --ago 90d "
az acr run --cmd $PURGE_CMD --registry $REGISTRY /dev/null
The images in the ACR does have tags
I tried to reproduce the same issue in my environment and got the below results
I have created the container registry
We have to push the image into container registry and while pushing we have to tag the image then only it will show the deleted items
The Acr purge container command will deletes the images by tag in a repository that match a name filter and that are older than a specific duration
The below example will delete the all image tags before one day
PURGE_CMD="acr purge --filter 'image_name:.*' \ --untagged --ago 1d"
az acr run \ --cmd "$PURGE_CMD" \ --registry <myregistry_name> \ /dev/null
The below example will take to create a daily schedule ACR task and will delete the images tags and manifest files more than 7 days.
I have only one image so it delete one tag image only
PURGE_CMD="acr purge --filter 'image_name:.*' \ --ago 7d"
az acr task create --name purgeTask \ --cmd "$PURGE_CMD" \ --schedule "0 0 * * *" \ --registry myregistry_name \ --context /dev/null
For more information use this Refernce

Ho can I purge all repository from Azure container registry without entering all repository one-by-ne

I am trying to clean few Azure container registry images from all repository. For now I am entering repository name one-by-one but this looks vary tedious like this.
PURGE_CMD="acr purge --filter 'aag:.*' --filter 'aap_6.0:.*' --ago 1d --untagged --keep 7"
az acr task create --name PurgeACRImages \
--cmd "$PURGE_CMD" \
--schedule "5 6 * * 1" \
--registry myregistry \
--timeout 18000 \
--context /dev/null
Here I have given name of two repository, now I have 800 repository and it's really hard to type 800 repository in this PURGE_CMD command.
I need a command through which I can select all repo from ACR and store into PURGE_CMD
We can loop on the output of az acr repository list to concatenate repository name filters to the PURGE_CMD variable.
If you are using a Linux client, run the following from the command line:
PURGE_CMD="acr purge --ago 1d --untagged --keep 7"
for i in $(az acr repository list -n <yourRegistryName> -o tsv);do PURGE_CMD+=" --filter '"$i":.'";done
echo $PURGE_CMD
If you are using Windows Powershell run the following from the command line:
$PURGE_CMD="acr purge --ago 1d --untagged --keep 7"
foreach ($i in $(az acr repository list -n <yourRegistryName> -o tsv)){$PURGE_CMD+=" --filter '"+$i+":.'"}
echo $PURGE_CMD
Note: replace <yourRegistryName> with the name of your Azure Container Registry.
Finally you can run:
az acr task create --name PurgeACRImages
--cmd "$PURGE_CMD"
--schedule "5 6 * * 1"
--registry myregistry
--timeout 18000
--context /dev/null
$PURGE_CMD="acr purge --filter '.*:.*' --ago 30d" command looks good for me. So, there are 2 expressions: for repo name and for tag name

How to get the currentSlot and change the helm upgrade command with the new slot on Azure devops?

I am trying to implement CI/CD pipeline for my APIs on AKS. i have successfully configured the CI and CD pipelines which works quite smoothly, now i have 2 environments named Prod and Slot to enable 0 down time.
I found the blue/green deployment method. And in my CD pipeline i am trying to set the current slot and pass it to the helm upgrade command in the next step
currentSlot=`(helm --client-only get values --all api-poi | grep -Po 'productionSlot: \K.*')`
if [ "$currentSlot" == "blue" ]; then
newSlot="green"
else
newSlot="blue"
fi
but it always set the newslot as empty. what could be the reason?
$(newSlot).enabled=true
Try with Azure CLI command instead of Bash script with the az aks get-credentials --name involved.
Alternate CLI command would be
az aks get-credentials --name $(AKSClusterName) --resource-group $(AKSResourceGroup)
currentSlot=$(helm get values --all $(chartName) | grep -oP '(?<=productionSlot: ).*')
if [ "$currentSlot" == "blue" ]; then
newSlot="green"
else
newSlot="blue"
fi
you need to set those AKSClusterName,AKSResourceGroup,chartName values in the pipeline or hard code them

Retrieve list of repositories and their tag versions in one call

I have two azure CLI queries.
az acr repository list
to retrieve a list of repositories in my container registry
az acr repository show-tags
to retrieve version tag for each of the repositories returned by the first query
This results in an initial call to retrieve a list and then 1 call for each repository returned. Is there an alternative that would reduce the number of calls required to one? Retrieval of a list of repositories and their version in 1 go.
show-tags command needs a repository parameter that is mandatory and I am unaware of any other commands that would return the information I need.
As of now, it's impossible to complete it in one call.
As someone already mentioned, the least call step is to create a script to get all the repositories(store the repositories in a variable), then in a loop, use az acr repository show-tags to get their tags.
The sameple scripts as blow:
result="$(az acr repository list -n ACR_name --output tsv)"
for i in $result; do az acr repository show-tags -n ACR_name --repository $i; done
Test result as below:
AFAIK currently there is no alternative that would retrieve list of repositories and their versions in one go. I recommend sharing this feedback by posting it here -> https://feedback.azure.com/forums/903958-azure-container-registry
Just a suggestion which you might already be aware of is, for now as a workaround you may develop a small script to fetch all the repositories using the list command and feed each repository name in sequence one after the other as input to the show tags command and concatenate the outputs of all repositories.
Hope this helps!!
To get a list of full images names that you can use with docker pull, do this:
export REGISTRY=mycontainerregistry
#!/bin/bash
mycontainers=$(az acr repository list --name $REGISTRY --output tsv)
for i in $mycontainers
do
echo -n "$REGISTRY.azurecr.io/$i:"
az acr repository show-tags -n $REGISTRY --repository $i --output tsv|tail -1
done
I tried the above script posted by bbaassssiiee, and it appears to work to retrieve just the latest images. If you'd like to generate a list of ALL images in a repository using a IMAGE_REPO:TAG format, I created the following bash script similar to the one above to do exactly that:
#!/bin/bash
registry_name='REGISTRY_NAME'
destination='LOCATION_TO_STORE_LIST'
az acr login --name $registry_name
touch $destination
repos="$(az acr repository list -n $registry_name --output tsv)"
for i in $repos; do
images="$(az acr repository show-tags -n $registry_name --repository $i --output tsv --orderby time_desc)"
for j in $images; do
echo $i":"$j >> $destination;
done;
done;
The only variables you need to set are registry_name and destination to store the list. I wanted to do a little cleanup of our container registry because there are a lot of unused images so the idea was to identify which images we need to keep from the list, remove them, and then create a script to run az acr repository delete against the remaining images to clean up the registry and decrease the amount of storage we're using for the container registry to avoid unnecessary costs.

Azure CLI: delete all untagged images within a repository in one command

I am storing my docker images in a private repository on Azure. Everytime I push an image to that repository with the same tag (e.g., latest), the previous image becomes untagged, but remains in the repository. This has led to stacking a lot of untagged images, in the repository. I would like a command, using the azure cli, to delete all the untagged images in just one go.
For instance, typing the following command:
az acr repository show-manifests -n myRegistry --repository myRepo
returned several manifests for the d24-staging-fuzzy-search-srv repository:
[
{
"digest": "sha256:blablabla1",
"tags": null,
"timestamp": "t1"
},
{
"digest": "sha256:blablabla2",
"tags": null,
"timestamp": "t2"
},
{
"digest": "sha256:blablabla3",
"tags": [
"latest"
],
"timestamp": "t3"
}]
I would like to have a command in azure cli that deletes all the mainfests that have a tag of "null" and keep the one that has the tag "latest"
Try to use the command below.
az acr repository delete -n yourRegistry --image yourRepo:null
For more details, refer to this article.
Delete an image by tag. This deletes the manifest referenced by 'hello-world:latest', all other tags referencing the manifest, and any associated layer data.
az acr repository delete -n MyRegistry --image hello-world:latest
In case someone is still wondering what is the one liner command to accomplish this, please use the following Bash Script:
az acr repository show-manifests -n <registryName> --repository <repositoryName> --query "[?tags[0]==null].digest" -o tsv | xargs -I% az acr repository delete -n <registryName> -t <repositoryName>#% -y
Source: https://learn.microsoft.com/en-us/azure/container-registry/container-registry-faq
Header: How do I delete all manifests that are not referenced by any tag in a repository?
For Linux bash
az acr repository show-manifests -n myRegistry --repository myRepository --query "[?tags[0]==null].digest" -o tsv | xargs -I% az acr repository delete -n myRegistry -t myRepository#% --yes
For Windows PowerShell:
az acr repository show-manifests -n myRegistry --repository myRepository --query "[?tags[0]==null].digest" -o tsv | %{ az acr repository delete -n myRegistry -t myRepository#$_ --yes }
I ended up creating a node script, in which I injected azure cli commands using shelljs.
Basically what I did is, For each repository, I fetched all its manifests, and for each manifests that does not contain the label "latest" was deleted

Resources