In this short blog post, I will be sharing a PowerShell script designed to help clean up orphaned metric alerts in your Azure environment. Orphaned alerts are those that are associated with resources that no longer exist, each of those unnecessary alerts can cost about 10 cents, which can add up over time.
This script will:
- List all metric alerts in your subscription and then filter them based on specific criteria, such as the resource group name and the scope.
- Check if the associated resource exists and, if not, it will remove the orphaned alert.
While it is currently configured to remove logic apps related alerts (indicated by the “-la” naming convention), it can be configured to suit your requirements and metric alerts for any Azure resource type.
- Be cautious when using this script as removing metric alerts is irreversible.
- Verify the script’s operation in a non-production environment before using it in a production environment.
- Ensure that you have the necessary permissions to remove alerts and resources in the Azure Subscription.
- Ensure you have Azure PowerShell installed in your local machine and authenticated via Connect-AzAccount.
- Once logged in, set the Azure Context to the subscription where the metric alerts reside using the script below:
set-azcontext -subscription "replace with subscription ID"
- Download the PS script above to your local machine: https://github.com/harris-kristanto/harris-blog/blob/main/AzureMetricAlertsCleanup.ps1
- Open the PowerShell script in your preferred text editor.
- Locate the line with the comment
“# Filter alerts to only UAT RGs"and replace
"**dr*"with the desired resource group name filter. For example, you can use
"**prod"to match resource groups that contain “prod” in the name.
- Still looking at the same line, replace the scope with the resource type that you want to remove the alerts from, if removing logic apps related alerts, then use “*-la”.
- “Scope” is the name of the Azure resource that a given metric alert is configured for.
- Save the changes to the script and open a PowerShell terminal with appropriate permissions.
- Do a “cd” to the directory where the script is located and run the script by executing the command .\AzureMetricAlertsCleanup.ps1
- The script will list all metric alerts in your subscription, it will display a count of the total orphaned alerts removed.
- Once the execution is complete, verify that all the removed alerts are deleted in Azure Portal (note that there might be a minute or two delay before the deletion is reflected in Azure Portal)