Last active
September 16, 2019 19:12
-
-
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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
#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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.