⚡ Leverage Serverless Microsoft Azure Functions and Azure Alerts to ensure application availability
Tags: serverless, azure, azurefunctions, devops
Published: 2019-09-16 15:35:43


## Table Of Contents
 * [Overview](#Overview)
 * [Scenario](#Scenario)
 * [Leverage Serverless Microsoft Azure Functions to automate resource deployment via Azure Resource Manager](#Leverage Serverless Microsoft Azure Functions to automate resource deployment via Azure Resource Manager)
   + [Provision Azure Function](#Provision Azure Function)
   + [Configure Azure Function](#Configure Azure Function)
   + [Configure alerts on the resource](#Configure alerts on the resource)
 * [Testing](#Testing)
 * [See Also](#See also)



## Overview <a name="Overview"></a>
Hello  Folks!

On this article we will review how to effectively make use of Azure Functions and Azure alerts to ensure application availability. I will demonstrate how to leverage Azure Functions and Azure Alerts to enable an automated failover for a Virtual Machine on Azure.

While Azure Functions are intended for processing data, integrating systems, working with the internet-of-things (IoT), and building simple APIs and microservices, this approach is to validate the potential capabilities of serverless components.

## Scenario <a name="Scenario"></a>
While you can build redundancies at the virtual machine (VM), datacenter, and regional levels based on your business needs, in this case I had a very unlikely situation in which an organization was trying to use Azure Site Recovery to replicate the Kemp Virtual LoadMaster to a secondary region, however the mobility service Agentfrom the Azure Site Recovery to enable the replica wasn’t compatible with the [Kemp load balancer for Azure](https://azuremarketplace.microsoft.com/en-us/marketplace/apps/kemptech.vlm-azure). 


![01-Leverage Serverless Microsoft Azure Functions and Azure Alerts to ensure application availability-dave-rendon](https://thepracticaldev.s3.amazonaws.com/i/25gke8ucmm9fjrurpti2.jpg)


This multinational professional services company that provides services in strategy, consulting, digital, technology and operations wanted to perform a Disaster Recovery solution for all their services living on a specific Azure US Region and try to minimize RPO/RTO by enabling Azure Site Recovery to a second US Region. 

Given the limitations to install the mobility service agent on the Virtual Machine to enable the replica job, there are 2 potential solutions: 

1. Enable the LoadMaster GEO to distribute traffic across 2 Azure regions and then leverage 2 LoadMasters in HA mode to distribute traffic to the local servers and applications
1. Leverage Serverless Microsoft Azure Functions and Azure Alerts to monitor the VM running on the primary site and in the case of a potential failure use the Azure Function to spin up the Infrastructure resources on the secondary region.

For the sake of this discussion I will demonstrate you how to leverage Serverless Microsoft Azure Functions and Azure Alerts and I suggest you to take a look on how to Azure Functions to start/stop resources.

With this approach you could enable a proactive monitoring and enable real time healthchecks on the primary Virtual Machine(VM), so that if the VM fails the healthcheck then you can trigger the Azure Function to start the VM on the second region

![02-Leverage Serverless Microsoft Azure Functions and Azure Alerts to ensure application availability-dave-rendon](https://thepracticaldev.s3.amazonaws.com/i/vofpk5o5zbcmk33ittzz.png)

## Leverage Serverless Microsoft Azure Functions to automate resource deployment via Azure Resource Manager<a name="Leverage Serverless Microsoft Azure Functions to automate resource deployment via Azure Resource Manager"></a>


### Pre-requisites

I assume you have the following:
1. Active Azure Subscription.
1. ARM Template(.json file) of your resource(s)

Steps to leverage Serverless Microsoft Azure Functions to automate resource deployment via Azure Resource Manager

1. Provision Azure Function
1. Configure Azure Function
1. Configure Alerts on the resource:

### Provision Azure Function<a name="Provision Azure Function"></a>


- Go to the Azure Portal and create a new resource from Template: 


 ![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/o7t88fdkmgou5k3yws8r.png)

 ![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/hgxn3p04dbw0ac959euk.png)

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/u1fyziypotozzxuuudoz.png)





- Create your Azure Function based on a consumption plan using the following Github Repo:
	
	https://github.com/daveRendon/kemp/blob/master/tools/templates/azure-function.json
	
	
-  Copy the json template form the URL above and paste it on the editor: 

  ![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/v4qj5fms99daj7wwatmd.png)




- Then click save 

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/066yhhxt4hw0kyjgax9l.png)




- Now provide the parameters for your Azure Function as shown below:
	
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/2nmtaeeoeanenfumfr0q.png)


TIP. "Azure Functions comes in two main flavors, consumption and dedicated. The difference between the two is important, choosing one over the other not only dictates the behavior of your application but also how you’re billed. The consumption plan is our “serverless” model, your code reacts to events, effectively scales out to meet whatever load you’re seeing, scales down when code isn’t running, and you’re billed only for what you use. Plus, all of this happens without you thinking about what Microsoft Azure is doing behind the scenes.

The dedicated plan on the other hand, involves renting control of a virtual machine. This control means you can do whatever you like on that machine. It’s always available and might make more sense financially if you have a function which needs to run 24/7."


- Once provisioned you should see the Azure Function as below: 

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/11uk812590bnzm6dgvwb.png)



## Configure Azure Function<a name="Configure Azure Function"></a>
- Now click on create a new Function and select the HTTP Trigger type: 

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/7whbi7j4umhjkgp2v67x.png)


- Now provide the name and authorization level for your Function and click create: 

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/mlyfw4d7w9rdzfos3guh.png)


You should see the code below: 

```javascript
module.exports = async function(context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');
    if (req.query.name || (req.body && req.body.name)) {
        context.res = {
            // status: 200, /* Defaults to 200 */
            body: "Hello " + (req.query.name || req.body.name)
        };
    } else {
        context.res = {
            status: 400,
            body: "Please pass a name on the query string or in the request body"
        };
    }
};
```

For the purpose of the demonstration just copy the code below which will redirect to the ARM template to provision the resources. In this case the Azure Function will redirect to the json that will be provisioned.

```javascript
module.exports = function(context, req){
    var url = "https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2FdaveRendon%2Fkemp%2Fmaster%2Ftools%2Ftemplates%2Fvlm-200-az-function-template.json";
    context.res =  {
        status: 302,
        headers: {
            Location: url
        }
    }
    context.done();
}
```

- Now click Save and Run. For testing purposes you can get the URL from the Azure Function and execute it on your browser: 


![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/eojpp2c6jgg1owunkbft.png)

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/xznu2pxotv3371x84h7e.png)


URL example: 

```javascript
https://provision-app.azurewebsites.net/api/HttpTriggerKempVLM?code=Qe6aB7umn1CWgkI8KkaO5yBu0RmtEybGlHnLmPhJhXPUxRkWS1TXtg==
```

- Once you navigate to this url you should be redirected to the ARM deployment:

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/pkv5tj3j0f1q52vm2a5z.png)


## Configure alerts on the resource<a name="Configure alerts on the resource"></a>


- Go to the Resource in this case the LoadMaster is living on a virtual machine, then scroll down on the main options blade and select Alerts, then click on "New alert rule" :

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/vhr44ywbvcqle2n3dtkf.png)


- In order to create a rule you need to select the resource target, then validate a condition to trigger the alert and then define the actions you want to enable. Click Add under Condition:

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/yyvpnlmnt6mwnaqu5dbx.png)


- Then choose the Percentage CPU metric 


![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/s211aip03wejpmtgpx34.png)


- Now configure the alert logic. In this case we want to ensure that the resource is up and running so set the threshold to static and select the operator "less than", aggregation type "Average" and Value = 1 

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/z29mvgsigog3poftz1kr.png)


- This will ensure that the alert will be triggered whenever the percentage cpu is less than 1 percent. 

- Now click on "Create action group" under Actions as shown below:

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/6fhakzsao65b1qle3x11.png)

- Provide the parameters for the action group as below:

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/lmro3extipg4xkpp83rn.png)

- Now associate the Azure Function to the Alert: 

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/r9rfu4e26lek0jjr6fj5.png)

- Now click OK twice.


## Testing<a name="Testing"></a>

1. Ensure that the Resource in this case the VM is up and running
1. Ensure that the alert is enabled
1. Ensure that the Azure Function is enabled.


### Test Process

1. Stop the VM
1. Review the Azure Function Live Metrics - you should see a incoming request
1. Optionally execute manually the trigger on the Function.



## See also<a name="See also"></a>
 - https://azure.microsoft.com/en-us/blog/understanding-serverless-cold-start/
 - https://docs.microsoft.com/en-us/azure/azure-monitor/platform/alerts-metric-overview
 - https://stackoverflow.com/questions/40838619/azure-function-role-like-permissions-to-stop-azure-virtual-machines/40883318#40883318
 - https://docs.microsoft.com/en-us/rest/api/azure/