Skip to content

Files

Latest commit

71b4953 · Feb 11, 2022

History

History
192 lines (139 loc) · 12.1 KB

custom-event-to-function.md

File metadata and controls

192 lines (139 loc) · 12.1 KB
title description ms.date ms.topic ms.custom ms.devlang
Quickstart: Send custom events to Azure Function - Event Grid
Quickstart: Use Azure Event Grid and Azure CLI or portal to publish a topic, and subscribe to that event. An Azure Function is used for the endpoint.
09/28/2021
quickstart
mode-other, devx-track-azurecli
azurecli

Quickstart: Route custom events to an Azure Function with Event Grid

Azure Event Grid is an eventing service for the cloud. Azure Functions is one of the supported event handlers. In this article, you use the Azure portal to create a custom topic, subscribe to the custom topic, and trigger the event to view the result. You send the events to an Azure Function.

[!INCLUDE quickstarts-free-trial-note.md]

Create Azure Function

Before subscribing to the custom topic, create a function to handle the events.

  1. Create a function app using instructions from Create a function app.

  2. On the Function App page, select Functions on the left menu.

  3. Select +Create on the toolbar to create a function.

  4. On the Create Function page, follow these steps:

    1. This step is optional. For Development environment, select the development environment that you want to use to work with the function code.

    2. Select Azure Event Grid Trigger in the Select a template section.

    3. Enter a name for the function. In this example, it's HandleEventsFunc.

      :::image type="content" source="./media/custom-event-to-function/function-event-grid-trigger.png" lightbox="./media/custom-event-to-function/function-event-grid-trigger.png" alt-text="Select Event Grid trigger.":::

  5. Use the Code + Test page to see the existing code for the function and update it.

    :::image type="content" source="./media/custom-event-to-function/function-code-test-menu.png" alt-text="Image showing the selection Code + Test menu for an Azure function.":::

[!INCLUDE event-grid-register-provider-portal.md]

Create a custom topic

An event grid topic provides a user-defined endpoint that you post your events to.

  1. Sign in to Azure portal.

  2. Select All services on the left navigational menu, search for Event Grid, and select Event Grid Topics.

    :::image type="content" source="./media/custom-event-to-function/select-event-grid-topics.png" alt-text="Image showing the selection of Event Grid Topics.":::

  3. On the Event Grid Topics page, select + Add on the toolbar.

    :::image type="content" source="./media/custom-event-to-function/add-event-grid-topic-button.png" alt-text="Image showing the Create button to create an event grid topic.":::

  4. On the Create Topic page, follow these steps:

    1. Select your Azure subscription.

    2. Select the same resource group from the previous steps.

    3. Provide a unique name for the custom topic. The topic name must be unique because it's represented by a DNS entry. Don't use the name shown in the image. Instead, create your own name - it must be between 3-50 characters and contain only values a-z, A-Z, 0-9, and "-".

    4. Select a location for the event grid topic.

    5. Select Review + create.

      :::image type="content" source="./media/custom-event-to-function/create-custom-topic.png" alt-text="Image showing the Create Topic page.":::

    6. On the Review + create page, review settings and select Create.

  5. After the custom topic has been created, select Go to resource link to see the following Event Grid Topic page for the topic you created.

    :::image type="content" source="./media/custom-event-to-function/event-grid-topic-home-page.png" alt-text="Image showing the home page for your Event Grid custom topic.":::

Subscribe to custom topic

You subscribe to an event grid topic to tell Event Grid which events you want to track, and where to send the events.

  1. Now, on the Event Grid Topic page for your custom topic, select + Event Subscription on the toolbar.

    :::image type="content" source="./media/custom-event-to-function/new-event-subscription.png" alt-text="Image showing the selection of Add Event Subscription on the toolbar.":::

  2. On the Create Event Subscription page, follow these steps:

    1. Enter a name for the event subscription.

    2. Select Azure Function for the Endpoint type.

    3. Choose Select an endpoint.

      :::image type="content" source="./media/custom-event-to-function/provide-subscription-values.png" alt-text="Image showing event subscription values.":::

    4. For the function endpoint, select the Azure Subscription and Resource Group your Function App is in and then select the Function App and function you created earlier. Select Confirm Selection.

      :::image type="content" source="./media/custom-event-to-function/provide-endpoint.png" alt-text="Image showing the Select Azure Function page showing the selection of function you created earlier.":::

    5. This step is optional, but recommended for production scenarios. On the Create Event Subscription page, switch to the Advanced Features tab, and set values for Max events per batch and Preferred batch size in kilobytes.

      Batching can give you high-throughput. For Max events per batch, set maximum number of events that a subscription will include in a batch. Preferred batch size sets the preferred upper bound of batch size in kilo bytes, but can be exceeded if a single event is larger than this threshold.

      :::image type="content" source="./media/custom-event-to-function/enable-batching.png" alt-text="Image showing batching settings for an event subscription.":::

    6. On the Create Event Subscription page, select Create.

Send an event to your topic

Now, let's trigger an event to see how Event Grid distributes the message to your endpoint. Use either Azure CLI or PowerShell to send a test event to your custom topic. Typically, an application or Azure service would send the event data.

The first example uses Azure CLI. It gets the URL and key for the custom topic, and sample event data. Use your custom topic name for <topic name>. It creates sample event data. The data element of the JSON is the payload of your event. Any well-formed JSON can go in this field. You can also use the subject field for advanced routing and filtering. CURL is a utility that sends HTTP requests.

Azure CLI

  1. In the Azure portal, select Cloud Shell. Select Bash in the top-left corner of the Cloud Shell window.

    :::image type="content" source="./media/custom-event-quickstart-portal/cloud-shell-bash.png" alt-text="Image showing Cloud Shell - Bash window":::

  2. Run the following command to get the endpoint for the topic: After you copy and paste the command, update the topic name and resource group name before you run the command.

    endpoint=$(az eventgrid topic show --name <topic name> -g <resource group name> --query "endpoint" --output tsv)
    
  3. Run the following command to get the key for the custom topic: After you copy and paste the command, update the topic name and resource group name before you run the command.

    key=$(az eventgrid topic key list --name <topic name> -g <resource group name> --query "key1" --output tsv)
    
  4. Copy the following statement with the event definition, and press ENTER.

    event='[ {"id": "'"$RANDOM"'", "eventType": "recordInserted", "subject": "myapp/vehicles/motorcycles", "eventTime": "'`date +%Y-%m-%dT%H:%M:%S%z`'", "data":{ "make": "Ducati", "model": "Monster"},"dataVersion": "1.0"} ]'
  5. Run the following Curl command to post the event:

    curl -X POST -H "aeg-sas-key: $key" -d "$event" $endpoint
    

Azure PowerShell

The second example uses PowerShell to perform similar steps.

  1. In the Azure portal, select Cloud Shell (alternatively go to https://shell.azure.com/). Select PowerShell in the top-left corner of the Cloud Shell window. See the sample Cloud Shell window image in the Azure CLI section.

  2. Set the following variables. After you copy and paste each command, update the topic name and resource group name before you run the command:

    $resourceGroupName = <resource group name>
    $topicName = <topic name>
  3. Run the following commands to get the endpoint and the keys for the topic:

    $endpoint = (Get-AzEventGridTopic -ResourceGroupName $resourceGroupName -Name $topicName).Endpoint
    $keys = Get-AzEventGridTopicKey -ResourceGroupName $resourceGroupName -Name $topicName
  4. Prepare the event. Copy and run the statements in the Cloud Shell window.

    $eventID = Get-Random 99999
    
    #Date format should be SortableDateTimePattern (ISO 8601)
    $eventDate = Get-Date -Format s
    
    #Construct body using Hashtable
    $htbody = @{
        id= $eventID
        eventType="recordInserted"
        subject="myapp/vehicles/motorcycles"
        eventTime= $eventDate   
        data= @{
            make="Ducati"
            model="Monster"
        }
        dataVersion="1.0"
    }
    
    #Use ConvertTo-Json to convert event body from Hashtable to JSON Object
    #Append square brackets to the converted JSON payload since they are expected in the event's JSON payload syntax
    $body = "["+(ConvertTo-Json $htbody)+"]"
  5. Use the Invoke-WebRequest cmdlet to send the event.

    Invoke-WebRequest -Uri $endpoint -Method POST -Body $body -Headers @{"aeg-sas-key" = $keys.Key1}

Verify that function received the event

You've triggered the event, and Event Grid sent the message to the endpoint you configured when subscribing. Navigate to your Event Grid triggered function and open the logs. You should see a copy of the data payload of the event in the logs. If you don't make sure you open the logs window first, or hit reconnect, and then try sending a test event again.

:::image type="content" source="./media/custom-event-to-function/successful-function.png" alt-text="Image showing the Monitor view of the Azure function with a log.":::

Clean up resources

If you plan to continue working with this event, don't clean up the resources created in this article. Otherwise, delete the resources you created in this article.

  1. Select Resource Groups on the left menu. If you don't see it on the left menu, select All Services on the left menu, and select Resource Groups.

  2. Select the resource group to launch the Resource Group page.

  3. Select Delete resource group on the toolbar.

  4. Confirm deletion by entering the name of the resource group, and select Delete.

    Resource groups

    The other resource group you see in the image was created and used by the Cloud Shell window. Delete it if you don't plan to use the Cloud Shell window later.

Next steps

Now that you know how to create topics and event subscriptions, learn more about what Event Grid can help you do:

See the following samples to learn about publishing events to and consuming events from Event Grid using different programming languages.