Working with Azure Monitor Rest API

It might be an edge case, or you are creating your own integration. But chances are, after fiddling around with Azure Monitor Rest API, you encounter a situation where you would have work with its API.
Personally, I have numerous situations over the last years, that required me to integrate directly with Azure Management APIs

In this blog post, I will help you get started using the APIs, hopefully making it less intimidating. All code examples will use PowerShell.

Create SPN and assign it to your subscription RBAC

I am using a service principal in order to connect programmatically to Azure. SPNs are created in Azure Active Directory as Application Registrations. You can choose whether you want to do this via the portal, or by using PowerShell.

After creating (or using an existing SPN) grant the application appropriate access. For simplicity, I am using contributor to my subscription. That might be best for you as well, but one should always use the least privileged assignment needed.

Consider the above as a prerequisite for you to continue.

At this point, you should have an application registration, a secret, and a role assignment on your subscription. We can now use this to acquire an access token and connect to Azure Monitor’s REST API.

Connect to Azure Monitor API using PowerShell

Azure Monitor APIs are a part of the Azure Management APIs. I will, therefore, use these names interchangeably. Also keep in mind, that all other APIs under Azure Management will follow the same methods I demonstrate for Azure Monitor.

To query data we need to authenticate. In the example below, I am using client credentials to acquire the access token. Microsoft’s official example is using the ADAL method, connecting with your identity. I have never had the use for this, as I am usually writing integrations service-to-service.
If you are creating an interactive portal and want to leverage the user’s authorization, ADAL (or MSAL) are probably better.

# getting a token from login.microsoft.com
$tenantID = “martinehrnst.onmicrosoft.com”
$subscriptionId = “”
$myCustomAPPID = “https://management.azure.com/.default”
$ClientID = ‘fc6e7910-97d9-4bea-8bff-d364ae749502’
$ClientKey = ”
$params = @{
scope = $myCustomAPPID;
grant_type = ‘client_credentials’;
client_id = $ClientId;
client_secret = $ClientKey;
}
$AADToken = Invoke-RestMethod -Method Post -Uri “https://login.microsoftonline.com/$tenantID/oauth2/v2.0/token” -Body $params
# creating an authentication header
$headers = @{
Authorization = “Bearer ” + $AADToken.access_token
}

view rawget-accessToken.ps1 hosted with ❤ by GitHub


Retrieve Azure Monitor alert rules

I have no idea why you are exploring Azure Monitors API. Providing an integration solution is therefore not possible. But my gut feeling is that alerts and metrics is a good place to start.

Azure Monitor Rest API

When working with alerts, we need to work with multiple endpoints. Depending on what you are working on, these are the most common;

We can start with one of the basics, retrieve the current configured alert rules. To do that, we need to know what kind it is. The classic alert rules (old type) use a single endpoint, while the current use it’s own.

Below I have included three endpoints and a screenshot. As you can see, all the information that you expect is to be found in the output. From here we can start to explore the alert rule by accessing its properties.

# get current configured alert rules
# classic (old) alert rules
$classic = Invoke-RestMethod -Method Get -Uri “https://management.azure.com/subscriptions/$subscriptionId/providers/microsoft.insights/alertrules?api-version=2016-03-01” -Headers $headers
# metric alert rules
$metricRules = Invoke-RestMethod -Method Get -Uri “https://management.azure.com/subscriptions/$subscriptionId/providers/Microsoft.Insights/metricAlerts?api-version=2018-03-01” -Headers $headers
# activity log alert rules
$activityLogRules = Invoke-RestMethod -Method Get -Uri “https://management.azure.com/subscriptions/$subscriptionId/providers/microsoft.insights/activityLogAlerts?api-version=2017-04-01” -Headers $headers

view rawget-configuredAlertRules.ps1 hosted with ❤ by GitHub

Azure Monitor Rest API

Get resource metrics from Azure Monitors API

Metrics is another fundamental in monitoring. When we work with the API in the context of metrics. You can explore the available metrics for each resource type by using the Metric Definitions endpoint.

Actual metrics values require a bit more when it comes to the actual query. The official documentation describes everything pretty well, but I have provided an example for a VM below. This example shows the basics of how you get data from one metric and one VM. You can add multiple metrics to one query, and do additional filtering using the OData filter.

# Getting metrics for a VM
# timespan last 24h
# formatting as sortable ISO string and adding both dates to one variable
$endTime = (get-date).ToString(“s”)
$startTime = (get-date).AddHours(-24).ToString(“s”)
$timespan = $startTime + “/” + $endTime
$metricName = “Disk Read Bytes”
$resourceId = “$subscriptionId/resourceGroups/Demo-VMs-RG/providers/Microsoft.Compute/virtualMachines/VMNAME3/” # adding as a variable to make it easier to read URI
Invoke-RestMethod -Method GET -Uri “https://management.azure.com/subscriptions/$resourceId/providers/microsoft.insights/metrics?api-version=2018-01-01&metricnames=$metricName&timespan=$timeSpan” -Headers $headers

view rawget-resourceMetrics.ps1 hosted with ❤ by GitHub

Azure Monitor Rest API

Manage alerts, updating status, etc.

Viewing configured alert rules, looking at disk metrics for a VM. What about alerts. The actual things that send you emails- can we work with them using this API? Yes, you can.

Like I said. Providing an integration solution in this blog post isn’t possible. but most integrations I have seen with Azure Monitor or other monitoring solutions have had some kind of functionality to handle active alerts. Personally, I have created one for SquaredUp earlier, where we could acknowledge alerts in Azure Monitor as well as our on-premises SCOM installation.

Before we wrap up. Let’s take a look at how we can interact with an active alert. I have configured a very naggy alert rule, creating a lot of noise, and I want to change the status of those alerts. Armed with PowerShell and the alerts management endpoints everything is possible.

Azure Monitor Rest API
# alert handeling
# updating alert status
# get alerts
$alerts = Invoke-RestMethod -Method Get -Uri “https://management.azure.com/subscriptions/$subscriptionId/providers/Microsoft.AlertsManagement/alerts?api-version=2018-05-05” -Headers $headers
# fore every alert I have. get it’s ID and acknowledge it.
# pay attention to the method is now POST (one can debate if this should be a PUT)
foreach ($alert in $alerts.value) {
$alertId = $alert.id
Invoke-RestMethod -method POST -uri “https://management.azure.com$alertId/changeState?api-version=2018-05-05&newState=Acknowledged” -Headers $headers
}
Azure Monitor Rest API

Summary

This blog post has covered the basics regarding the Azure Monitor REST API and PowerShell. With the examples above and the official documentation, you can start creating your own solutions and integrations.

While we have only covered how to get data out of Azure Monitor, you should know it’s also possible to inject data. By using the HTTP data collector API and the Metric store possibilities are ‘endless’.

Integrations ideas

  • Alert remediation/handling from a ticketing system
  • Dashboarding with third-party or custom web integration
  • Teams/Slack/IM connector
  • Custom application metrics or logs

In my examples, I have purposely not included how new alert rules are created, as I believe this should be done through ARM. If that is your use case, you should know it is possible and fully supported.

About the Author:

I am a Microsoft Azure MVP, currently working as a technical lead for Azure at Intility. For more than a decade I have worked with infrastructure management, automation, and monitoring. As this traditional role is changing fast, I am focusing my community contributions around the new IT-Pro role, where code meets operations. I regularly share on my blog, social media, conferences, and user groups.

Want to Learn More?
Check out 10 Azure Cloud Services that Every Developer, Consultant, and Architect Should Know and Learn It Well.

Reference:

Ehrnst, M. (2020). Working with Azure Monitor Rest API. Available at: https://adatum.no/azure/azure-monitor/working-with-azure-monitor-rest-api [Accessed: 20th May 2020].

Share this on...

Rate this Post:

Share:

Topics:

Azure