Member-only story
Purge all messages from Azure Service Bus Queue
As I’m using Azure Service Bus as message queue, I got a need to clean all messages from a queue, that includes dead letters. I searched a little from the internet and the solution is quite laborious(Using Service Bus Explorer or a .NET code). That’s the reason that I chose to do it myself by calling Service Bus API, I think that will be much easier for use case. And I wrote a script for automation as well.
Just to be clear, this task in only for Service Bus queue. I think these steps are useful and I will summarize them including the details. Of course, there are also some shell script codes I wrote for the task, I will share it as well.
The very beginning of this solution is this link: https://docs.microsoft.com/en-us/rest/api/servicebus/receive-and-delete-message-destructive-read#see-also
This link introduces a way to read and delete message from an active message queue. However, it doesn’t provide a way to remove the message from dead letter queue. So, It causes me thinking, is it a way to get dead letter queue API and call with the same method?
Let’s do it then.

I retrieved the API from the develop mode. The API is basically identical to the active message queue API. It’s https://{SERVICENAMESPACE}.servicebus.windows.net/{QUEUE_NAME}/$DeadLetterQueue/messages/head
I got the API, so my next task is to generate SAS token for authorization. Please notice that $ need to be interpret as \$ in shell or it will be transfer as variable and cause unexpected failure.
To generate the API, there are numerous way to do it. But, you will need the connection string first. In case you don’t need how to get it, I will show the way first.
Portal:
In your Service Bus namespace, Settings->Shared access policies->RootManageSharedAccessKey, and then copy Connection String.
AZ Cli:
az servicebus namespace authorization-rule keys list - resource-group myresourcegroup - namespace-name mynamespace - name myauthorule
Once you got the connection string, you can generate the SAS token by following this document: https://docs.microsoft.com/en-us/rest/api/eventhub/generate-sas-token.