Hello!

The saga continues with deleting deployments for linked templates… come to find out that deleting linked templates serially can be extremely slow. So I updated my script to parallelise the deletion of the templates. Fortunately ForEach-Object has a parallel feature and can throttle the number of threads. It’s quite neat that each deplyoyment has all the info in it so the script block is able to reference the object for all it needs. This is probably programming as it should be and I’m just used to less.

Anyway, worth noting that the linked templates generated by the ADF npm package have hardcoded deployment names. I think it is the name of the repo that is used? Not entirely sure. This is fine when you’re deploying one ADF to one Resource Group, but this is not always the case for development sandboxes. So before I deploy the ADF I read the contents of the master template and run a find/replace in Resources for type deployments and update the name, leaving the number intact. It helps that the deployment name is the same prefix so the script below will filter out all the ones I want to delete.

In terms of time saved, it takes about 10 minutes to delete 42 templates serially but only 2 minutes in parallel. And considering that it takes over ten minutes to deploy the ARM template now it’s a welcome time saver.

[CmdletBinding()]
param (
    [Parameter()]
    [String]
    $ResourceGroupName,

    [Parameter()]
    [String]
    $DeploymentName
)

Write-Host "Deleting ARM deployment ... under resource group: $ResourceGroupName"
$deployments = Get-AzResourceGroupDeployment -ResourceGroupName $ResourceGroupName
$deployments | Where-Object {$_.DeploymentName -like "$DeploymentName*"} | ForEach-Object -Parallel {
    Write-Host "Deployment to be deleted: "$_.DeploymentName
    $deploymentOperations = Get-AzResourceGroupDeploymentOperation -DeploymentName $_.deploymentName -ResourceGroupName $_.ResourceGroupName
    $deploymentsToDelete = $deploymentOperations | Where-Object { $_.properties.targetResource.id -like "*Microsoft.Resources/deployments*" }
    $deploymentsToDelete | ForEach-Object -Parallel {
        Write-Host "Deleting inner deployment: $($_.properties.targetResource.id)"
        Remove-AzResourceGroupDeployment -Id $_.properties.targetResource.id
    } -ThrottleLimit 16
    Write-Host "Deleting deployment:" $_.deploymentName
    Remove-AzResourceGroupDeployment -ResourceGroupName $_.ResourceGroupName -Name $_.deploymentName
} -ThrottleLimit 16