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.
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.
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.
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.
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).
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"
- using System.Net;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Primitives;
- using Newtonsoft.Json;
-
- public class EventGridSubscriber
- {
- public object[] EventGridEvent {get;set;}
- public EventGridEvent[] DeserializeEventGridEvents(string json)
- {
- return JsonConvert.DeserializeObject<EventGridEvent[]>(json);
- }
- }
-
- public class EventGridEvent
- {
- public string id {get;set;}
- public dynamic data {get;set;}
- public string topic {get;set;}
- public string subject {get;set;}
- public string eventType {get;set;}
- }
-
- public class SubscriptionValidationEventData
- {
- public string validationCode {get;set;}
- }
-
- public class SubscriptionValidationResponse
- {
- public string validationResponse {get;set;}
- }
-
- public static async Task<IActionResult> Run(HttpRequestMessage req, ILogger log)
- {
- string response = string.Empty;
-
- string requestContent = await req.Content.ReadAsStringAsync();
-
- EventGridSubscriber eventGridSubscriber = new EventGridSubscriber();
-
- EventGridEvent[] eventGridEvents = eventGridSubscriber.DeserializeEventGridEvents(requestContent);
-
- foreach (EventGridEvent eventGridEvent in eventGridEvents)
- {
- if (eventGridEvent.eventType == "Microsoft.EventGrid.SubscriptionValidationEvent")
- {
-
- var eventData = eventGridEvent.data.ToObject<SubscriptionValidationEventData>();
- log.LogInformation($"REGISTRATION: {eventGridEvent.topic}");
-
- var responseData = new SubscriptionValidationResponse()
- {
- validationResponse = eventData.validationCode
- };
-
- return (ActionResult)new OkObjectResult(responseData);
- }
-
-
- log.LogInformation($"UNKNOWN REQUEST: {requestContent}");
- }
-
- return (ActionResult)new OkObjectResult(response);
- }
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.
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.
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.
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.
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.
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.