Search code examples
azure-cognitive-servicesazure-cliazure-rest-api

How to list and purge deleted Azure Cognitive Services resources in the current subscription with Azure CLI


When redeploying Azure Cognitive Services resources I get this error message

{"code": "FlagMustBeSetForRestore", "message": "An existing resource with ID '/subscriptions/12345678-1234-5678-0912-12345678/resourceGroups/my-rg/providers/Microsoft.CognitiveServices/accounts/aiServices-lgzzxhdw6ffhu' has been soft-deleted. To restore the resource, you must specify 'restore' to be 'true' in the property. If you don't want to restore existing resource, please purge it first."}

How can I just delete such - in my case trial resources - in one go?


Solution

  • How to purge deleted accounts in documented in: https://learn.microsoft.com/th-th/azure/ai-services/recover-purge-resources?tabs=azure-cli#purge-a-deleted-resource

    Azure REST API provides and operation to list deleted accounts: https://learn.microsoft.com/en-us/rest/api/aiservices/accountmanagement/deleted-accounts/list?view=rest-aiservices-accountmanagement-2023-05-01&tabs=HTTP

    Combining this into a Bash script helped me to delete those resources in one go with Azure CLI:

    #!/bin/sh
    SUBSCRIPTION_ID=`az account show --query id -o tsv`
    az rest --method get \
      --uri "/subscriptions/$SUBSCRIPTION_ID/providers/Microsoft.CognitiveServices/deletedAccounts?api-version=2023-05-01" \
      --query "value[].id" -o tsv | xargs -r az resource delete --ids