Azure alerts via SMS using Clockwork SMS

I have a bunch of azure alerts set up that I really need to worry about, so for me SMS is the best way to make sure that I don't miss them. This is a quick post about how I got that setup.

Ingredients

  • A Clockwork SMS account. Other SMS providers do exist, but I know Clockwork well, so it was a no-brainer for me. Get yourself setup at www.clockworksms.com.
  • An azure account. But then, you're reading about setting up azure alerts, so you already have one of those!

Recipe

So to do this we're going to use the new "serverless" function apps from azure. They're perfect for this ad-hoc kind of thing, we don't need to worry about deployment, servers, etc.. We can just write some code, and run it in the cloud!

So - Create a new function app. I'm not providing screenshots here, it's all easy to find in Azure. For this, I have my function apps tied to the cheapest app service plan, it's not going to need many resources! If you need more help around creating a new function app, I'll pass you on to Troyhunt :)

We need to create a new function app, so when you get a list of templates, choose "Generic webhook - C#". So now, we have an endpoint that we can hit via HTTP, and when we hit it, we can run some code. Now we just need to fill in the code!

So - Azure alerts all share the same common JSON payload, which looks like this:

{
"status": "Activated",
"context": {
            "timestamp": "2015-08-14T22:26:41.9975398Z",
            "id": "/subscriptions/s1/resourceGroups/useast/providers/microsoft.insights/alertrules/ruleName1",
            "name": "ruleName1",
            "description": "some description",
            "conditionType": "Metric",
            "condition": {
                        "metricName": "Requests",
                        "metricUnit": "Count",
                        "metricValue": "10",
                        "threshold": "10",
                        "windowSize": "15",
                        "timeAggregation": "Average",
                        "operator": "GreaterThanOrEqual"
                },
            "subscriptionId": "s1",
            "resourceGroupName": "useast",                                
            "resourceName": "mysite1",
            "resourceType": "microsoft.foo/sites",
            "resourceId": "/subscriptions/s1/resourceGroups/useast/providers/microsoft.foo/sites/mysite1",
            "resourceRegion": "centralus",
            "portalLink": "https://portal.azure.com/#resource/subscriptions/s1/resourceGroups/useast/providers/microsoft.foo/sites/mysite1"
},
"properties": {
              "key1": "value1",
              "key2": "value2"
              }
}

We can grab the fields we care about out of the JSON payload, and build an SMS message to send viaclockwork. The code looks like this:

#r "Newtonsoft.Json"

using System;
using System.Net;
using Newtonsoft.Json;

public static async Task<object> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info($"Webhook was triggered!");

    string jsonContent = await req.Content.ReadAsStringAsync();

    dynamic data = JsonConvert.DeserializeObject(jsonContent);

    var message = WebUtility.UrlEncode($"Azure alert: {data.context.name} ({data.context.description})");

    // Send the alert VIA Clockwork SMS
    var smsEndpoint = $"https://api.clockworksms.com/http/send.aspx?Key=CLOCKWORK_KEY&To=447123123&Content={message}";

    var client = new HttpClient();
    HttpResponseMessage response = await client.GetAsync(smsEndpoint);
    if (response.IsSuccessStatusCode)
    {
        return req.CreateResponse(HttpStatusCode.OK);
    }

    return req.CreateResponse(HttpStatusCode.InternalServerError);

}

Here, we take the json payload, deserialize to a dynamic object, and then build up a message with the bits we need. We then build up a SMS Http request (smsEndpoint), with the information we want. You'll need to change the phone number, and set CLOCKWORK_KEY to a valid clockwork API key.

All that remains now, is to take the Function URL for my new function app, and paste that into the webhook url property for my Azure alerts. So when my azure alert triggers, it'll post to my function app, which will then send me a SMS while I'm out walking the dog!

Simples!

Comments powered by Disqus