Microsoft Docs

Azure Functions Event Grid Bindings

This document describes how to use Event Grid triggers and bindings in Azure Functions.

Overview

Azure Event Grid is a fully managed event routing service that enables you to easily build applications with an event-driven architecture. Event Grid uses publish-subscribe models to route events from event sources to event handlers.

Azure Functions can integrate with Event Grid to trigger functions in response to events or to publish events to Event Grid.

Event Grid Trigger

The Event Grid trigger allows your function to react to events published by Event Grid. When an event is received, the function is executed with the event data.

Trigger Configuration

To configure an Event Grid trigger, you specify the following:

Example (C#)

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.EventGrid;
using Microsoft.Azure.EventGrid.Models;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;

public static class EventGridTriggerFunction
{
    [FunctionName("EventGridTriggerCSharp")]
    public static void Run(
        [EventGridTrigger] EventGridEvent eventGridEvent,
        ILogger log)
    {
        log.LogInformation($"Event Subject: {eventGridEvent.Subject}");
        log.LogInformation($"Event Topic: {eventGridEvent.Topic}");
        log.LogInformation($"Event Type: {eventGridEvent.EventType}");
        log.LogInformation($"Event Data: {eventGridEvent.Data.ToString()}");
    }
}

Example (JavaScript)

module.exports = async function (context, eventGridEvent) {
    context.log(`Event Subject: ${eventGridEvent.subject}`);
    context.log(`Event Topic: ${eventGridEvent.topic}`);
    context.log(`Event Type: ${eventGridEvent.eventType}`);
    context.log(`Event Data: ${JSON.stringify(eventGridEvent.data)}`);
};

Event Grid Output Binding

The Event Grid output binding allows your function to publish events to an Event Grid topic.

Binding Configuration

To configure an Event Grid output binding, you specify the following:

Example (C#)

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.EventGrid;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Threading.Tasks;

public static class EventGridOutputFunction
{
    [FunctionName("EventGridOutputCSharp")]
    public static async Task Run(
        [TimerTrigger("0 */5 * * * *")] TimerInfo myTimer,
        [EventGrid(TopicEndpointUri = "%EventGridTopicEndpoint%", AccessKey = "%EventGridAccessKey%")] IAsyncCollector events,
        ILogger log)
    {
        log.LogInformation($"C# Timer trigger function executed at: {System.DateTime.Now}");

        var eventData = new { message = "Hello from Azure Functions!" };

        var myEvent = new EventGridEvent
        {
            Topic = "/subscriptions/{your-subscription-id}/resourceGroups/{your-resource-group}/providers/Microsoft.EventGrid/topics/{your-topic-name}",
            Subject = "azureFunctions/timerTrigger",
            EventType = "MyCustomEvent",
            EventTime = System.DateTime.UtcNow,
            Id = System.Guid.NewGuid().ToString(),
            Data = eventData
        };

        await events.AddAsync(myEvent);
        log.LogInformation("Published event to Event Grid.");
    }
}

Example (JavaScript)

const { EventGridManager } = require('azure-actions-eventgrid');

module.exports = async function (context, myTimer) {
    if (myTimer.isPastDue) {
        context.log('JavaScript is running late!');
    }
    context.log('JavaScript timer trigger function executed!');

    const topicEndpoint = process.env.EventGridTopicEndpoint;
    const accessKey = process.env.EventGridAccessKey;

    const eventGridManager = new EventGridManager(topicEndpoint, accessKey);

    const eventData = {
        message: "Hello from Azure Functions!"
    };

    const eventPayload = [{
        topic: '/subscriptions/{your-subscription-id}/resourceGroups/{your-resource-group}/providers/Microsoft.EventGrid/topics/{your-topic-name}',
        subject: 'azureFunctions/timerTrigger',
        eventType: 'MyCustomEvent',
        eventTime: new Date().toISOString(),
        id: context.invocationId,
        data: eventData
    }];

    await eventGridManager.publishEvents(eventPayload);
    context.log('Published event to Event Grid.');
};

Important Notes:

  • Ensure your function app has the necessary permissions to access Event Grid topics.
  • For output bindings, use application settings or Azure Key Vault to store your topic endpoint and access key securely.
  • The EventGridEvent model includes essential properties like Topic, Subject, EventType, EventTime, Id, and Data.