How To Register An HTTP Webhook Azure Function With The Azure Event Grid

While we won’t build additional logic beyond this point, you can easily build on top of this sample code to start reacting to Azure provisioning events.
 

Overview

 
Microsoft Azure’s event grid is a very powerful automation platform that allows you to synchronize configuration tasks, and implement custom monitoring solutions to your deployed infrastructure. There are multiple ways to integrate with the Event Grid, including messaging and more generic endpoints such as HTTP Webhooks.
 
To show how Webhooks work with the Event Grid, we will create an Azure Function that responds to the registration event of the Event Grid, and outputs all further incoming payloads to we can see the Event Grid payload. We will call this event OnNewResourceCreated.
 
How Register An HTTP Webhook Azure Function With The Azure Event Grid
 

Create a new Azure Function

 
Let’s create an Azure Function App; we will name it OnNewResourceCreated. In the Function App creation form, select an existing Resource Group, or create a new one. Select the Windows Operating System, the Consumption Plan, and the location of the service (I am choosing South Central US where I already have a storage account in this data center). Leave the runtime as .NET Core, and click on Create. If you are reusing existing resources, make sure they are in the same region for performance and cost reasons.
 
How Register An HTTP Webhook Azure Function With The Azure Event Grid
 
Once created, you will see the OnNewResourceCreated App Service in your list of available services, within which we will create the function. To do so, click on the OnNewResourceCreated App Service and click on the New Function button.
 
How Register An HTTP Webhook Azure Function With The Azure Event Grid
 
For simplicity, we will choose an In-Portal function so that we can add the source code directly in the browser without using Visual Studio.
 
How Register An HTTP Webhook Azure Function With The Azure Event Grid
 
Then select the Webhook + API function and click on Create. This creates an HTTP Trigger (called HttpTrigger1 in my environment; you can rename the function as desired).
 
How Register An HTTP Webhook Azure Function With The Azure Event Grid
 
Select the newly created function so you can edit the source code (you can see the function created on the left-side menu under Functions). The inline editor opens the run.csx file that we will modify next.
 

Handle the Registration Logic

 
Let’s paste the following code in the Azure Function we just created (partial credit to the Microsoft documentation) to handle the registration event that Event Grid requires. The code returns an HTTP 200 response with the registration validation code when requested, and outputs the complete request payload for all other requests for debugging purposes.
 
#r "Newtonsoft.Json" 
  1. using System.Net;  
  2. using Microsoft.AspNetCore.Mvc;  
  3. using Microsoft.Extensions.Primitives;  
  4. using Newtonsoft.Json;  
  5.   
  6. public class EventGridSubscriber  
  7. {  
  8.     public object[] EventGridEvent {get;set;}  
  9.     public EventGridEvent[] DeserializeEventGridEvents(string json)  
  10.     {  
  11.         return JsonConvert.DeserializeObject<EventGridEvent[]>(json);  
  12.     }  
  13. }  
  14.   
  15. public class EventGridEvent  
  16. {  
  17.     public string id {get;set;}  
  18.     public dynamic data {get;set;}  
  19.     public string topic {get;set;}  
  20.     public string subject {get;set;}  
  21.     public string eventType {get;set;}  
  22. }  
  23.   
  24. public class SubscriptionValidationEventData  
  25. {  
  26.     public string validationCode {get;set;}  
  27. }  
  28.   
  29. public class SubscriptionValidationResponse  
  30. {  
  31.     public string validationResponse {get;set;}  
  32. }   
  33.   
  34. public static async Task<IActionResult> Run(HttpRequestMessage req, ILogger log)  
  35. {  
  36.     string response = string.Empty;  
  37.   
  38.     string requestContent = await req.Content.ReadAsStringAsync();  
  39.   
  40.     EventGridSubscriber eventGridSubscriber = new EventGridSubscriber();  
  41.   
  42.     EventGridEvent[] eventGridEvents = eventGridSubscriber.DeserializeEventGridEvents(requestContent);  
  43.   
  44.     foreach (EventGridEvent eventGridEvent in eventGridEvents)  
  45.     {  
  46.         if (eventGridEvent.eventType == "Microsoft.EventGrid.SubscriptionValidationEvent")  
  47.         {  
  48.               
  49.             var eventData = eventGridEvent.data.ToObject<SubscriptionValidationEventData>();  
  50.             log.LogInformation($"REGISTRATION: {eventGridEvent.topic}");  
  51.   
  52.             var responseData = new SubscriptionValidationResponse()  
  53.             {  
  54.                 validationResponse = eventData.validationCode  
  55.             };  
  56.   
  57.             return (ActionResult)new OkObjectResult(responseData);  
  58.         }  
  59.   
  60.         // Log the request  
  61.         log.LogInformation($"UNKNOWN REQUEST: {requestContent}");  
  62.     }  
  63.   
  64.     return (ActionResult)new OkObjectResult(response);  
  65. }  

Registering the Azure Function with the EventGrid

 
Now that the Azure Function is ready we can configure the Event Grid to forward events to the function. To do so, I will create an event on an existing Resource Group by clicking on the Events tab and choose to create a new event subscription.
 
How Register An HTTP Webhook Azure Function With The Azure Event Grid
 
In the next screen, enter a name for the event, choose the Resource Action Success event, and choose the Webhook endpoint type. Click on Select and endpoint, and enter the Azure Function URL (previously copied) into the Subscriber Endpoint field, and click Create. 
 
How Register An HTTP Webhook Azure Function With The Azure Event Grid
 
After clicking on Create, the event calls the Azure Function with the registration code that the function returns. You can see below the output of the function when this happens.
 
How Register An HTTP Webhook Azure Function With The Azure Event Grid
 
The Azure Function is now registered to process events in the selected Resource Group.
 

Seeing it in Action

 
To test our Azure Function, let’s add a new service to the Resource Group. From the Overview tab of the Resource Group select Add. Select the Face service, enter the necessary information and click Create.
 
How Register An HTTP Webhook Azure Function With The Azure Event Grid
 
Within a few minutes, the Azure Function is called by the Event Grid with the details of the event (multiple events could be generated; for example creating this new service generates three separate validation events). The Azure Function prints the payload in the debug window of the Azure Function.
 
How Register An HTTP Webhook Azure Function With The Azure Event Grid
 
At this point, the Azure Function is ready to accept events from the event that we created in the Resource Group. It becomes possible to integrate these events to perform additional automation tasks and logging/auditing.


Similar Articles