Skip to content

Instantly share code, notes, and snippets.

@bmoore-msft
Last active September 16, 2019 19:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmoore-msft/e2b5f65dcf8f52e8e2ec230e544d0371 to your computer and use it in GitHub Desktop.
Save bmoore-msft/e2b5f65dcf8f52e8e2ec230e544d0371 to your computer and use it in GitHub Desktop.
Delete Deployments from a ResourceGroup Using Jobs and a Service Principal
#
#this script will delete deployments from a resourceGroup if the number of deployments exceeds the number specified by the Max parameter
#
Param(
[string] [Parameter(Mandatory = $true)] $ResourceGroupName,
[int] [Parameter(Mandatory = $true)] $Max,
[string] [Parameter(Mandatory = $true)] $tenantId,
[string] [Parameter(Mandatory = $true)] $ServicePrincipalId,
[securestring] [Parameter(Mandatory = $true)] $ServicePrincipalSecret,
[string] [Parameter(Mandatory = $true)] $SubscriptionId
)
$creds = New-Object System.Management.Automation.PSCredential ($ServicePrincipalId, $ServicePrincipalSecret)
Connect-AzAccount -ServicePrincipal -Credential $creds -TenantId $tenantId
Set-AzContext -Subscription $SubscriptionId
$deployments = Get-AzResourceGroupDeployment -ResourceGroupName $ResourceGroupName
if ($deployments.Count -gt $Max) {
$numToDelete = $deployments.Count - $Max
$i = 1
while ($i -le $numToDelete) {
write-host "Deleting Deployment: "$deployments[$deployments.Count - $i].DeploymentName
Start-Job -Name $deployments[$deployments.Count - $i].DeploymentName {
Param($RGName, $deploymentName, $creds, $tenantId, $SubscriptionId)
Connect-AzAccount -ServicePrincipal -Credential $creds -TenantId $tenantId
Set-AzContext -Subscription $SubscriptionId
Remove-AzResourceGroupDeployment -ResourceGroupName $RGName -Name $deploymentName -Verbose
} -ArgumentList $ResourceGroupName, $deployments[$deployments.Count - $i].DeploymentName, $creds, $tenantId, $SubscriptionId
$i++
}
}
Get-Job | Wait-Job | Receive-Job
@bmoore-msft
Copy link
Author

Azure PowerShell doesn't always handle context in jobs correctly, so the script forces a login for each job. This works fine but requires passing Service Principal Credentials to the script.

See: this gist for a simpler serial version of the script.

Alternatively, you could get the token from the cache for the current context.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment