Azure App Gateway Routing Rule Priority in PowerShell

How to use rule priorities with the Add-AzApplicationGatewayRequestRoutingRule cmdlet.

There’s been a recent update to the Azure API which broke some automation I had in place to configure Azure Application Gateways. Request Routing rules now require a Priority parameter to be passed, and for that parameter to be a unique value within the rules on that gateway. Details about this evaluation order can be found on the MS Docs website.

This means the PowerShell cmdlet Add-AzApplicationGatewayRequestRoutingRule needs to include the -Priority parameter, accompanied by a unique value. Adding the parameter is no problem, but it’s still necessary to work out that unique value. Without the -Priority parameter I was getting the error:

1Either all or no rule should have the priority specified.

And if the parameter was included but the value was not unique the following error was shown:

1Priority must be unique across all the request routing rules.

The first method I used to resolve this calculates the new priority by finding the highest existing priority and adding 1 to it. The maximum value (lowest priority) is 20000, so assuming no-one has manually entered a high number this should be reasonably safe.

1$Priority=(Get-AzApplicationGatewayRequestRoutingRule -ApplicationGateway $AppGW | 
2     Sort-Object -Property Priority | 
3     Select-Object Priority -Last 1).Priority +1

However, we can get a bit cleverer. The following PowerShell will find the next available priority starting at 100 and working up. So, for example, if the priority list is 100, 101, 102, 104 then this will pick the unused 103, rather than the previous method which would have picked 105.

1$values=(Get-AzApplicationGatewayRequestRoutingRule -ApplicationGateway $AppGW).Priority
2$priority=100; while($values -contains $priority){$priority+=1}