Purge a soft-deleted Azure API Management instance

Azure recently implemented a change to the API Management service whereby deleting the instance only puts it into a soft-deleted state rather than completely nuking it from orbit. This may be desirable for data recovery purposes but it means that if you run a terraform destroy on an environment with an APIM instance on it and then you try and rebuild that environment, it will fail due to the fact that the name you’re trying to use is being held onto by the previously removed instance. So since neither Azure CLI nor Az PowerShell natively support purging, I’m going to show you how to manually purge a soft-deleted Azure API Management instance.

NOTE: The below script uses the basic Az PowerShell tools but with a little elbow grease could be adapted to bash/zsh (provided you have a way of retrieving your Azure access token using OAuth).

$token = Get-AzAccessToken

$request = @{
    Method = 'DELETE'
    Uri    = "https://management.azure.com/subscriptions/{subscriptionGuid}/providers/Microsoft.ApiManagement/locations/{region}/deletedservices/{apimName}?api-version=2020-06-01-preview"
    Headers = @{
        Authorization = "Bearer $($token.Token)"
    }
}

Invoke-RestMethod @request

The only values you’ll need to supply are the subscriptionGuid, region, and apimName in the Uri.

Now the next time you’re stuck wondering why you can’t tear down and rebuild your environments with your IaC tool of choice, you’ll know how to purge a soft-deleted Azure API Management instance.

Source: Microsoft docs