I am trying to automate the infrastructure of my application. As part of that, I am creating Service Bus related resources (Namespace, Topics, Subscriptions) only if they do not exist. My subscriptions will only have 1 rule. So every time the script runs, it will delete all existing rules and create this rule from scratch.
Here's the pseudo code I am writing:
$topic = Get-AzServiceBusTopic -Name $TopicName -NamespaceName $NamespaceName -ResourceGroupName $ResourceGroupName -ErrorVariable notPresent -ErrorAction SilentlyContinue
if ($null -eq $topic -or $notPresent)
{
$topic = New-AzServiceBusTopic -Name TopicName -NamespaceName NamespaceName -ResourceGroupName ResourceGroupName -ErrorAction Stop
}
$subscription = Get-AzServiceBusSubscription -Name $SubscriptionName -TopicName $TopicName -NamespaceName $NamespaceName -ResourceGroupName $ResourceGroupName -ErrorVariable notPresent -ErrorAction SilentlyContinue
if ($null -eq $subscription -or $notPresent)
{
$subscription = New-AzServiceBusSubscription -Name SubscriptionName -TopicName TopicName -NamespaceName NamespaceName -ResourceGroupName ResourceGroupName -ErrorAction Stop
}
# forcefully delete existing rules
Get-AzServiceBusRule -SubscriptionName SubscriptionName -TopicName TopicName -NamespaceName NamespaceName -ResourceGroupName ResourceGroupName | Remove-AzServiceBusRule
# create rule
$rule = New-AzServiceBusRule -Name "`$Default" -SubscriptionName SubscriptionName -TopicName TopicName -NamespaceName NamespaceName -ResourceGroupName ResourceGroupName -FilterType SqlFilter -SqlExpression SqlFilterExpression -ErrorAction Stop
Randomly I am seeing New-AzServiceBusRule
Cmdlet call fails with the following error:
The messaging entity 'namespacename:Topic:topicname|subscriptionname|$Default' already exists. To know more visit | https://aka.ms/sbResourceMgrExceptions. TrackingId:823eeae9-8776-46e7-90de-5ec305e14bb5_B26, SystemTracker:NoSystemTracker, | Timestamp:2023-05-13T10:33:37
According to the documentation of New-AzServiceBusRule
, the cmdlet either creates a new rule and updates an existing rule. If that is the case, then why am I getting the resource exists exception.
I even tried waiting for a second before deleting all existing rules and creating the new rule but that did not help either.
Interesting thing is that it happens randomly. For some of the Subscriptions and Rules, the code works just fine and then randomly for one odd Subscription, it would fail. At times, it will not fail at all!
How can I prevent this from happening?