0

Looking in Azure portal I see this:

Alerts and Alert Rules in Azure Portal

Further I have run with great success the following cli commands:

az monitor metrics alert list --subscription  "$sub"
az monitor activity-log alert list --subscription  "$sub"

But for the life of me I cannot seem to find the correct API for managing alerts and alert rules using Python. Looking in the API reference, I see this:

Azure API categories relevant for alerts and alert rules

Please note Alert Processing Rule is mentioned but not Alert or Alert rule. Monitors are also mentioned. Are Monitors Alerts?

I have wrangled with online example code, API documentation and trippy LLMs to come up with this abomination:

def alert_rules(self, tag:str = None, do_debug = False):
    """
    List metric alerts across all subscriptions
    """
    rules = list()
    for subscription_id in self.subscriptions:
        if do_debug:
            logger.info(f"Looking for alert rules in sub {subscription_id}")
        try:
            monitor_client = self._monitor_client_for_sub(subscription_id)
            if monitor_client:
                if do_debug:
                    metric_alerts = list(monitor_client.metric_alerts.list_by_subscription())
                    scheduled_query_alerts = list(monitor_client.scheduled_query_rules.list_by_subscription())
                    logger.info(f"  Metric alerts retrieved: {devtools.pformat(metric_alerts)}")
                    logger.info(f"  Scheduled query alerts retrieved: {devtools.pformat(scheduled_query_alerts)}")
                
                resource_client = self._resource_client_for_sub(subscription_id)
                if resource_client:
                    resource_groups = [rg.name for rg in resource_client.resource_groups.list()]
                    for rg in resource_groups:
                        if do_debug:
                            logger.info(f"  Looking for alert rules in rg {rg}")
                        for rule in monitor_client.scheduled_query_rules.list_by_resource_group(rg):
                            logger.debug(f"    {rule}")
                            rules.append(rule)
                else:
                    if do_debug:
                        logger.warning(f"  No resource group client for {subscription_id}")
                # List all Metric Alert Rules
                for rule in monitor_client.metric_alerts.list_by_subscription():
                    logger.debug(f"  Scheduled Query Alert Rule: {rule}")
                    rules.append(rule)
                # List all Scheduled Query (Log) Alert Rules
                for rule in monitor_client.scheduled_query_rules.list_by_subscription():
                    logger.debug(f"  Scheduled Query Alert Rule: {rule}")
                    rules.append(rule)

                logs_query_client = self._logs_query_client_for_sub(subscription_id)
                if do_debug:
                    #logger.warning(f"Logs query client for {subscription_id}: {devtools.pformat(logs_query_client.__dict__)}")
                    pass
            else:
                if do_debug:
                    logger.warning(f"  No monitor client for {subscription_id}")
        except Exception as e:
            logger.error(f"* Error listing alert rules for sub {subscription_id}: {e}")
            return None
    if tag:
        if do_debug:
            logger.info(f"We have a tag to match: {tag}")
        alert_rules_with_tag = []
        for rule in rules:
            if rule.tags and tag in rule.tags:
                alert_rules_with_tag.append(rule)
        rules = alert_rules_with_tag
    else:
        if do_debug:
            logger.info(f"No tag")
    processed = list()
    for rule in rules:
        if do_debug:
            logger.info(f"Processing rule: {rule}")
        processed.append(self.process_rule(rule))

    return processed

It is a member function of my client class that tries desperately through many different means to simply list alert rules. It produces an empty list even when the cli command produces a good output.

So my question is, does this API exist? How should I list alert rules for my subscriptions?

1
  • Does this API exist? Yes it supports an API for metric and activity log alerts. @Mr. Developerdude Commented Oct 30, 2024 at 3:40

1 Answer 1

0

So my question is, does this API exist? How should I list alert rules for my subscriptions?

In my environment, I have some alert rules with different signal type.

Portal:

enter image description here

You can use the below python code that retrieves the required alert rules from the subscription.

Code:

from azure.identity import DefaultAzureCredential
from azure.mgmt.monitor import MonitorManagementClient

subscription_id = 'xxxx'

credentials = DefaultAzureCredential()

monitor_client = MonitorManagementClient(
    credential=credentials,
    subscription_id=subscription_id
)

    # Retrieve metric alerts
metric_alerts = monitor_client.metric_alerts.list_by_subscription()
for alert in metric_alerts:
    print("Metric Alert - Name:", alert.name, "| Type:", alert.type)

    # Retrieve activity log alerts
activity_log_alerts = monitor_client.activity_log_alerts.list_by_subscription_id()
for activity_alert in activity_log_alerts:
    print("Activity Log Alert - Name:", activity_alert.name, "| Type:", activity_alert.type)

    # Retrieve log search alerts (scheduled query rules)
log_search_alerts = monitor_client.scheduled_query_rules.list_by_subscription()
for log_alert in log_search_alerts:
    print("Log Search Alert - Name:", log_alert.name, "| Type:", log_alert.type)

Output:

Metric Alert - Name: testvenkat | Type: Microsoft.Insights/metricAlerts
Metric Alert - Name: venakt234 | Type: Microsoft.Insights/metricAlerts
Activity Log Alert - Name: venkat123 | Type: Microsoft.Insights/ActivityLogAlerts
Log Search Alert - Name: venkat456 | Type: Microsoft.Insights/scheduledQueryRules

enter image description here

Reference: Microsoft Azure SDK for Python | Microsoft Learn

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.