Skip to content

Latest commit

 

History

History
570 lines (395 loc) · 21.5 KB

functions-bindings-event-grid-trigger.md

File metadata and controls

570 lines (395 loc) · 21.5 KB
title description author ms.topic ms.date ms.author ms.custom
Azure Event Grid trigger for Azure Functions
Learn to run code when Event Grid events in Azure Functions are dispatched.
craigshoemaker
reference
02/14/2020
cshoe
fasttrack-edit, tracking-python

Azure Event Grid trigger for Azure Functions

Use the function trigger to respond to an event sent to an Event Grid topic.

For information on setup and configuration details, see the overview.

Example

For an HTTP trigger example, see Receive events to an HTTP endpoint.

C# (2.x and higher)

The following example shows a C# function that binds to EventGridEvent:

using Microsoft.Azure.EventGrid.Models;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.EventGrid;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;

namespace Company.Function
{
    public static class EventGridTriggerCSharp
    {
        [FunctionName("EventGridTest")]
        public static void EventGridTest([EventGridTrigger]EventGridEvent eventGridEvent, ILogger log)
        {
            log.LogInformation(eventGridEvent.Data.ToString());
        }
    }
}

For more information, see Packages, Attributes, Configuration, and Usage.

Version 1.x

The following example shows a Functions 1.x C# function that binds to JObject:

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.EventGrid;
using Microsoft.Azure.WebJobs.Host;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Microsoft.Extensions.Logging;

namespace Company.Function
{
    public static class EventGridTriggerCSharp
    {
        [FunctionName("EventGridTriggerCSharp")]
        public static void Run([EventGridTrigger]JObject eventGridEvent, ILogger log)
        {
            log.LogInformation(eventGridEvent.ToString(Formatting.Indented));
        }
    }
}

The following example shows a trigger binding in a function.json file and a C# script function that uses the binding.

Here's the binding data in the function.json file:

{
  "bindings": [
    {
      "type": "eventGridTrigger",
      "name": "eventGridEvent",
      "direction": "in"
    }
  ],
  "disabled": false
}

Version 2.x and higher

Here's an example that binds to EventGridEvent:

#r "Microsoft.Azure.EventGrid"
using Microsoft.Azure.EventGrid.Models;
using Microsoft.Extensions.Logging;

public static void Run(EventGridEvent eventGridEvent, ILogger log)
{
    log.LogInformation(eventGridEvent.Data.ToString());
}

For more information, see Packages, Attributes, Configuration, and Usage.

Version 1.x

Here's Functions 1.x C# script code that binds to JObject:

#r "Newtonsoft.Json"

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public static void Run(JObject eventGridEvent, TraceWriter log)
{
    log.Info(eventGridEvent.ToString(Formatting.Indented));
}

The following example shows a trigger binding in a function.json file and a JavaScript function that uses the binding.

Here's the binding data in the function.json file:

{
  "bindings": [
    {
      "type": "eventGridTrigger",
      "name": "eventGridEvent",
      "direction": "in"
    }
  ],
  "disabled": false
}

Here's the JavaScript code:

module.exports = function (context, eventGridEvent) {
    context.log("JavaScript Event Grid function processed a request.");
    context.log("Subject: " + eventGridEvent.subject);
    context.log("Time: " + eventGridEvent.eventTime);
    context.log("Data: " + JSON.stringify(eventGridEvent.data));
    context.done();
};

The following example shows a trigger binding in a function.json file and a Python function that uses the binding.

Here's the binding data in the function.json file:

{
  "bindings": [
    {
      "type": "eventGridTrigger",
      "name": "event",
      "direction": "in"
    }
  ],
  "disabled": false,
  "scriptFile": "__init__.py"
}

Here's the Python code:

import json
import logging

import azure.functions as func

def main(event: func.EventGridEvent):

    result = json.dumps({
        'id': event.id,
        'data': event.get_json(),
        'topic': event.topic,
        'subject': event.subject,
        'event_type': event.event_type,
    })

    logging.info('Python EventGrid trigger processed an event: %s', result)

This section contains the following examples:

The following examples show trigger binding in Java that use the binding and print out an event, first receiving the event as String and second as a POJO.

Event Grid trigger, String parameter

  @FunctionName("eventGridMonitorString")
  public void logEvent(
    @EventGridTrigger(
      name = "event"
    ) 
    String content, 
    final ExecutionContext context) {
      context.getLogger().info("Event content: " + content);      
  }

Event Grid trigger, POJO parameter

This example uses the following POJO, representing the top-level properties of an Event Grid event:

import java.util.Date;
import java.util.Map;

public class EventSchema {

  public String topic;
  public String subject;
  public String eventType;
  public Date eventTime;
  public String id;
  public String dataVersion;
  public String metadataVersion;
  public Map<String, Object> data;

}

Upon arrival, the event's JSON payload is de-serialized into the EventSchema POJO for use by the function. This process allows the function to access the event's properties in an object-oriented way.

  @FunctionName("eventGridMonitor")
  public void logEvent(
    @EventGridTrigger(
      name = "event"
    ) 
    EventSchema event, 
    final ExecutionContext context) {
      context.getLogger().info("Event content: ");
      context.getLogger().info("Subject: " + event.subject);
      context.getLogger().info("Time: " + event.eventTime); // automatically converted to Date by the runtime
      context.getLogger().info("Id: " + event.id);
      context.getLogger().info("Data: " + event.data);
  }

In the Java functions runtime library, use the EventGridTrigger annotation on parameters whose value would come from EventGrid. Parameters with these annotations cause the function to run when an event arrives. This annotation can be used with native Java types, POJOs, or nullable values using Optional<T>.


Attributes and annotations

In C# class libraries, use the EventGridTrigger attribute.

Here's an EventGridTrigger attribute in a method signature:

[FunctionName("EventGridTest")]
public static void EventGridTest([EventGridTrigger] JObject eventGridEvent, ILogger log)
{
    ...
}

For a complete example, see C# example.

Attributes are not supported by C# Script.

Attributes are not supported by JavaScript.

Attributes are not supported by Python.

The EventGridTrigger annotation allows you to declaratively configure an Event Grid binding by providing configuration values. See the example and configuration sections for more detail.


Configuration

The following table explains the binding configuration properties that you set in the function.json file. There are no constructor parameters or properties to set in the EventGridTrigger attribute.

function.json property Description
type Required - must be set to eventGridTrigger.
direction Required - must be set to in.
name Required - the variable name used in function code for the parameter that receives the event data.

Usage

In Azure Functions 1.x, you can use the following parameter types for the Event Grid trigger:

  • JObject
  • string

In Azure Functions 2.x and higher, you also have the option to use the following parameter type for the Event Grid trigger:

  • Microsoft.Azure.EventGrid.Models.EventGridEvent- Defines properties for the fields common to all event types.

Note

In Functions v1 if you try to bind to Microsoft.Azure.WebJobs.Extensions.EventGrid.EventGridEvent, the compiler will display a "deprecated" message and advise you to use Microsoft.Azure.EventGrid.Models.EventGridEvent instead. To use the newer type, reference the Microsoft.Azure.EventGrid NuGet package and fully qualify the EventGridEvent type name by prefixing it with Microsoft.Azure.EventGrid.Models.

In Azure Functions 1.x, you can use the following parameter types for the Event Grid trigger:

  • JObject
  • string

In Azure Functions 2.x and higher, you also have the option to use the following parameter type for the Event Grid trigger:

  • Microsoft.Azure.EventGrid.Models.EventGridEvent- Defines properties for the fields common to all event types.

Note

In Functions v1 if you try to bind to Microsoft.Azure.WebJobs.Extensions.EventGrid.EventGridEvent, the compiler will display a "deprecated" message and advise you to use Microsoft.Azure.EventGrid.Models.EventGridEvent instead. To use the newer type, reference the Microsoft.Azure.EventGrid NuGet package and fully qualify the EventGridEvent type name by prefixing it with Microsoft.Azure.EventGrid.Models. For information about how to reference NuGet packages in a C# script function, see Using NuGet packages

The Event Grid instance is available via the parameter configured in the function.json file's name property.

The Event Grid instance is available via the parameter configured in the function.json file's name property, typed as func.EventGridEvent.

The Event Grid event instance is available via the parameter associated to the EventGridTrigger attribute, typed as an EventSchema. See the example for more detail.


Event schema

Data for an Event Grid event is received as a JSON object in the body of an HTTP request. The JSON looks similar to the following example:

[{
  "topic": "/subscriptions/{subscriptionid}/resourceGroups/eg0122/providers/Microsoft.Storage/storageAccounts/egblobstore",
  "subject": "/blobServices/default/containers/{containername}/blobs/blobname.jpg",
  "eventType": "Microsoft.Storage.BlobCreated",
  "eventTime": "2018-01-23T17:02:19.6069787Z",
  "id": "{guid}",
  "data": {
    "api": "PutBlockList",
    "clientRequestId": "{guid}",
    "requestId": "{guid}",
    "eTag": "0x8D562831044DDD0",
    "contentType": "application/octet-stream",
    "contentLength": 2248,
    "blobType": "BlockBlob",
    "url": "https://egblobstore.blob.core.windows.net/{containername}/blobname.jpg",
    "sequencer": "000000000000272D000000000003D60F",
    "storageDiagnostics": {
      "batchId": "{guid}"
    }
  },
  "dataVersion": "",
  "metadataVersion": "1"
}]

The example shown is an array of one element. Event Grid always sends an array and may send more than one event in the array. The runtime invokes your function once for each array element.

The top-level properties in the event JSON data are the same among all event types, while the contents of the data property are specific to each event type. The example shown is for a blob storage event.

For explanations of the common and event-specific properties, see Event properties in the Event Grid documentation.

The EventGridEvent type defines only the top-level properties; the Data property is a JObject.

Create a subscription

To start receiving Event Grid HTTP requests, create an Event Grid subscription that specifies the endpoint URL that invokes the function.

Azure portal

For functions that you develop in the Azure portal with the Event Grid trigger, select Integration then choose the Event Grid Trigger and select Create Event Grid subscription.

:::image type="content" source="media/functions-bindings-event-grid/portal-sub-create.png" alt-text="Connect a new event subscription to trigger in the portal.":::

When you select this link, the portal opens the Create Event Subscription page with the current trigger endpoint already defined.

:::image type="content" source="media/functions-bindings-event-grid/endpoint-url.png" alt-text="Create event subscription with function endpoint already defined" :::

For more information about how to create subscriptions by using the Azure portal, see Create custom event - Azure portal in the Event Grid documentation.

Azure CLI

To create a subscription by using the Azure CLI, use the az eventgrid event-subscription create command.

The command requires the endpoint URL that invokes the function. The following example shows the version-specific URL pattern:

Version 2.x (and higher) runtime

https://{functionappname}.azurewebsites.net/runtime/webhooks/eventgrid?functionName={functionname}&code={systemkey}

Version 1.x runtime

https://{functionappname}.azurewebsites.net/admin/extensions/EventGridExtensionConfig?functionName={functionname}&code={systemkey}

The system key is an authorization key that has to be included in the endpoint URL for an Event Grid trigger. The following section explains how to get the system key.

Here's an example that subscribes to a blob storage account (with a placeholder for the system key):

Version 2.x (and higher) runtime

az eventgrid resource event-subscription create -g myResourceGroup \
--provider-namespace Microsoft.Storage --resource-type storageAccounts \
--resource-name myblobstorage12345 --name myFuncSub  \
--included-event-types Microsoft.Storage.BlobCreated \
--subject-begins-with /blobServices/default/containers/images/blobs/ \
--endpoint https://mystoragetriggeredfunction.azurewebsites.net/runtime/webhooks/eventgrid?functionName=imageresizefunc&code=<key>

Version 1.x runtime

az eventgrid resource event-subscription create -g myResourceGroup \
--provider-namespace Microsoft.Storage --resource-type storageAccounts \
--resource-name myblobstorage12345 --name myFuncSub  \
--included-event-types Microsoft.Storage.BlobCreated \
--subject-begins-with /blobServices/default/containers/images/blobs/ \
--endpoint https://mystoragetriggeredfunction.azurewebsites.net/admin/extensions/EventGridExtensionConfig?functionName=imageresizefunc&code=<key>

For more information about how to create a subscription, see the blob storage quickstart or the other Event Grid quickstarts.

Get the system key

You can get the system key by using the following API (HTTP GET):

Version 2.x (and higher) runtime

http://{functionappname}.azurewebsites.net/admin/host/systemkeys/eventgrid_extension?code={masterkey}

Version 1.x runtime

http://{functionappname}.azurewebsites.net/admin/host/systemkeys/eventgridextensionconfig_extension?code={masterkey}

This is an admin API, so it requires your function app master key. Don't confuse the system key (for invoking an Event Grid trigger function) with the master key (for performing administrative tasks on the function app). When you subscribe to an Event Grid topic, be sure to use the system key.

Here's an example of the response that provides the system key:

{
  "name": "eventgridextensionconfig_extension",
  "value": "{the system key for the function}",
  "links": [
    {
      "rel": "self",
      "href": "{the URL for the function, without the system key}"
    }
  ]
}

You can get the master key for your function app from the Function app settings tab in the portal.

Important

The master key provides administrator access to your function app. Don't share this key with third parties or distribute it in native client applications.

For more information, see Authorization keys in the HTTP trigger reference article.

Alternatively, you can send an HTTP PUT to specify the key value yourself.

Local testing with viewer web app

To test an Event Grid trigger locally, you have to get Event Grid HTTP requests delivered from their origin in the cloud to your local machine. One way to do that is by capturing requests online and manually resending them on your local machine:

  1. Create a viewer web app that captures event messages.
  2. Create an Event Grid subscription that sends events to the viewer app.
  3. Generate a request and copy the request body from the viewer app.
  4. Manually post the request to the localhost URL of your Event Grid trigger function.

When you're done testing, you can use the same subscription for production by updating the endpoint. Use the az eventgrid event-subscription update Azure CLI command.

Create a viewer web app

To simplify capturing event messages, you can deploy a pre-built web app that displays the event messages. The deployed solution includes an App Service plan, an App Service web app, and source code from GitHub.

Select Deploy to Azure to deploy the solution to your subscription. In the Azure portal, provide values for the parameters.

The deployment may take a few minutes to complete. After the deployment has succeeded, view your web app to make sure it's running. In a web browser, navigate to: https://<your-site-name>.azurewebsites.net

You see the site but no events have been posted to it yet.

View new site

Create an Event Grid subscription

Create an Event Grid subscription of the type you want to test, and give it the URL from your web app as the endpoint for event notification. The endpoint for your web app must include the suffix /api/updates/. So, the full URL is https://<your-site-name>.azurewebsites.net/api/updates

For information about how to create subscriptions by using the Azure portal, see Create custom event - Azure portal in the Event Grid documentation.

Generate a request

Trigger an event that will generate HTTP traffic to your web app endpoint. For example, if you created a blob storage subscription, upload or delete a blob. When a request shows up in your web app, copy the request body.

The subscription validation request will be received first; ignore any validation requests, and copy the event request.

Copy request body from web app

Manually post the request

Run your Event Grid function locally.

Use a tool such as Postman or curl to create an HTTP POST request:

  • Set a Content-Type: application/json header.
  • Set an aeg-event-type: Notification header.
  • Paste the RequestBin data into the request body.
  • Post to the URL of your Event Grid trigger function.
    • For 2.x and higher use the following pattern:

      http://localhost:7071/runtime/webhooks/eventgrid?functionName={FUNCTION_NAME}
      
    • For 1.x use:

      http://localhost:7071/admin/extensions/EventGridExtensionConfig?functionName={FUNCTION_NAME}
      

The functionName parameter must be the name specified in the FunctionName attribute.

The following screenshots show the headers and request body in Postman:

Headers in Postman

Request body in Postman

The Event Grid trigger function executes and shows logs similar to the following example:

Sample Event Grid trigger function logs

Next steps