Skip to content

Instantly share code, notes, and snippets.

@vukasinterzic
Created February 26, 2023 01:34
Show Gist options
  • Save vukasinterzic/fb5e4d42c18e9de7ebb37886eabb2489 to your computer and use it in GitHub Desktop.
Save vukasinterzic/fb5e4d42c18e9de7ebb37886eabb2489 to your computer and use it in GitHub Desktop.
# Get variables
$tagName = "ExpirationDate"
$prodTagValue = "Production"
$emailFrom = Get-AutomationVariable -Name "EmailFrom"
$emailTo = Get-AutomationVariable -Name "EmailTo"
$smtpServer = Get-AutomationVariable -Name "SmtpServer"
$logPath = "C:\Temp\AzureResourceGroupDeletion.log"
$daysBeforeExpiration = Get-AutomationVariable -Name "DaysBeforeExpiration"
# Get all resource groups with the ExpirationDate tag
$resourceGroups = Get-AzResourceGroup | Where-Object {$_.Tags.ContainsKey($tagName)}
# Loop through each resource group
foreach ($resourceGroup in $resourceGroups) {
# Check if the Environment tag equals Production, skip if it does
if ($resourceGroup.Tags.Environment -eq $prodTagValue) {
continue
}
# Get the expiration date from the ExpirationDate tag
$expirationDate = [datetime]::ParseExact($resourceGroup.Tags.ExpirationDate, "yyyy-MM-dd", $null)
# Check if the expiration date is less than the specified number of days from now
if ($expirationDate -lt (Get-Date).AddDays($daysBeforeExpiration)) {
# Send email notification that resource group will be deleted on expiration date
$subject = "Azure Resource Group will be deleted on $expirationDate"
$body = "The resource group $($resourceGroup.Name) will be deleted on $expirationDate."
Send-MailMessage -From $emailFrom -To $emailTo -Subject $subject -Body $body -SmtpServer $smtpServer
}
# Check if the expiration date has already passed
if ($expirationDate -lt (Get-Date)) {
# Try to remove the resource group
try {
Remove-AzResourceGroup -Name $resourceGroup.Name -Force -ErrorAction Stop
# Send email notification that resource group was deleted
$subject = "Azure Resource Group Deleted: $($resourceGroup.Name)"
$body = "The resource group $($resourceGroup.Name) was successfully deleted."
Send-MailMessage -From $emailFrom -To $emailTo -Subject $subject -Body $body -SmtpServer $smtpServer
}
# If removal fails, log the error and send an email summary
catch {
$errorMessage = $_.Exception.Message
Add-Content $logPath "$($resourceGroup.Name): $errorMessage"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment