Create a function triggered by a generic webhook

Azure Functions lets you execute your code in a serverless environment without having to first create a VM or publish a web application. For example, you can configure a function to be triggered by an alert raised by Azure Monitor. This topic shows you how to execute C# code when a resource group is added to your subscription.

Generic webhook triggered function in the Azure portal

Prerequisites

To complete this tutorial:

  • If you don't have an Azure subscription, create a free account before you begin.

Favorite Functions in the portal

If you haven't already done so, add Function Apps to your favorites in the Azure portal. This makes it easier to find your function apps. If you have already done this, skip to the next section.

  1. Log in to the Azure portal.

  2. Click the arrow at the bottom left to expand all services, type Functions in the Filter field, and then click the star next to Function Apps.

    Create function app in the Azure portal

    This adds the Functions icon to the menu on the left of the portal.

  3. Close the menu, then scroll down to the bottom to see the Functions icon. Click this icon to see a list of all your function apps. Click your function app to work with functions in this app.

    Function Apps in Favorites

Create an Azure Function app

  1. Click the New button found on the upper left-hand corner of the Azure portal, then select Compute > Function App.

    Create a function app in the Azure portal

  2. Use the function app settings as specified in the table below the image.

    Define new function app settings

    Setting Suggested value Description
    App name Globally unique name Name that identifies your new function app. Valid characters are a-z, 0-9, and -.
    Subscription Your subscription The subscription under which this new function app will be created.
    Resource Group myResourceGroup Name for the new resource group in which to create your function app.
    OS Windows Serverless hosting is currently only available when running on Windows. For Linux hosting, see Create your first function running on Linux using the Azure CLI.
    Hosting plan Consumption plan Hosting plan that defines how resources are allocated to your function app. In the default Consumption Plan, resources are added dynamically as required by your functions. In this serverless hosting, you only pay for the time your functions run.
    Location West Europe Choose a location near you or near other services your functions will access.
    Storage account Globally unique name Name of the new storage account used by your function app. Storage account names must be between 3 and 24 characters in length and may contain numbers and lowercase letters only. You can also use an existing account.
  3. Click Create to provision and deploy the new function app.

Next, you create a function in the new function app.

Create a generic webhook triggered function

  1. Expand your function app and click the + button next to Functions. If this function is the first one in your function app, select Custom function. This displays the complete set of function templates.

    Functions quickstart page in the Azure portal

  2. In the search field, type generic and then choose your desired language for the generic webhook trigger template. This topic uses a C# function.

    Choose the generic webhook trigger template

  3. Type a Name for your function, then select Create.

    Create a generic webhook triggered function in the Azure portal

  4. In your new function, click </> Get function URL, then copy and save the value. You use this value to configure the webhook.

    Review the function code

Next, you create a webhook endpoint in an activity log alert in Azure Monitor.

Create an activity log alert

  1. In the Azure portal, navigate to the Monitor service, select Alerts, and click Add activity log alert.

    Monitor

  2. Use the settings as specified in the table:

    Create an activity log alert

    Setting Suggested value Description
    Activity log alert name resource-group-create-alert Name of the activity log alert.
    Subscription Your subscription The subscription you are using for this tutorial.
    Resource Group myResourceGroup The resource group that the alert resources are deployed to. Using the same resource group as your function app makes it easier to clean up after you complete the tutorial.
    Event category Administrative This category includes changes made to Azure resources.
    Resource type Resource groups Filters alerts to resource group activities.
    Resource Group
    and Resource
    All Monitor all resources.
    Operation name Create Resource Group Filters alerts to create operations.
    Level Informational Include informational level alerts.
    Status Succeeded Filters alerts to actions that have completed successfully.
    Action group New Create a new action group, which defines the action takes when an alert is raised.
    Action group name function-webhook A name to identify the action group.
    Short name funcwebhook A short name for the action group.
  3. In Actions, add an action using the settings as specified in the table:

    Add an action group

    Setting Suggested value Description
    Name CallFunctionWebhook A name for the action.
    Action type Webhook The response to the alert is that a Webhook URL is called.
    Details Function URL Paste in the webhook URL of the function that you copied earlier.
  4. Click OK to create the alert and action group.

The webhook is now called when a resource group is created in your subscription. Next, you update the code in your function to handle the JSON log data in the body of the request.

Update the function code

  1. Navigate back to your function app in the portal, and expand your function.

  2. Replace the C# script code in the function in the portal with the following code:

    #r "Newtonsoft.Json"
    
    using System;
    using System.Net;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    
    public static async Task<object> Run(HttpRequestMessage req, TraceWriter log)
    {
        log.Info($"Webhook was triggered!");
    
        // Get the activityLog object from the JSON in the message body.
        string jsonContent = await req.Content.ReadAsStringAsync();
        JToken activityLog = JObject.Parse(jsonContent.ToString())
            .SelectToken("data.context.activityLog");
    
        // Return an error if the resource in the activity log isn't a resource group. 
        if (activityLog == null || !string.Equals((string)activityLog["resourceType"], 
            "Microsoft.Resources/subscriptions/resourcegroups"))
        {
            log.Error("An error occured");
            return req.CreateResponse(HttpStatusCode.BadRequest, new
            {
                error = "Unexpected message payload or wrong alert received."
            });
        }
    
        // Write information about the created resource group to the streaming log.
        log.Info(string.Format("Resource group '{0}' was {1} on {2}.",
            (string)activityLog["resourceGroupName"],
            ((string)activityLog["subStatus"]).ToLower(), 
            (DateTime)activityLog["submissionTimestamp"]));
    
        return req.CreateResponse(HttpStatusCode.OK);    
    }
    

Now you can test the function by creating a new resource group in your subscription.

Test the function

  1. Click the resource group icon in the left of the Azure portal, select + Add, type a Resource group name, and select Create to create an empty resource group.

    Create a resource group.

  2. Go back to your function and expand the Logs window. After the resource group is created, the activity log alert triggers the webhook and the function executes. You see the name of the new resource group written to the logs.

    Add a test application setting.

  3. (Optional) Go back and delete the resource group that you created. Note that this activity doesn't trigger the function. This is because delete operations are filtered out by the alert.

Clean up resources

Other quick starts in this collection build upon this quick start. If you plan to continue on to work with subsequent quick starts or with the tutorials, do not clean up the resources created in this quick start.

If you do not plan to continue, click the Resource group for the function app in the portal, and then click Delete.

Select the resource group to delete from the function app.

Next steps

You have created a function that runs when a request is received from a generic webhook.

Learn how to create functions with other kinds of triggers or how to integrate functions with other Azure services.

For more information about webhook triggers, see Azure Functions HTTP and webhook bindings. To learn more about developing functions in C#, see Azure Functions C# script developer reference.