Create and route custom events with Azure PowerShell and Event Grid

Azure Event Grid is an eventing service for the cloud. In this article, you use the Azure PowerShell to create a custom topic, subscribe to the topic, and trigger the event to view the result. Typically, you send events to an endpoint that responds to the event, such as, a webhook or Azure Function. However, to simplify this article, you send the events to a URL that merely collects the messages. You create this URL by using a third-party tool from Hookbin.

Note

Hookbin isn't intended for high throughput usage. The use of this tool is purely demonstrative. If you push more than one event at a time, you might not see all of your events in the tool.

When you're finished, you see that the event data has been sent to an endpoint.

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

This article requires that you are running the latest version of Azure PowerShell. If you need to install or upgrade, see Install and configure Azure PowerShell.

Create a resource group

Event Grid topics are Azure resources, and must be placed in an Azure resource group. The resource group is a logical collection into which Azure resources are deployed and managed.

Create a resource group with the New-AzureRmResourceGroup command.

The following example creates a resource group named gridResourceGroup in the westus2 location.

New-AzureRmResourceGroup -Name gridResourceGroup -Location westus2

Create a custom topic

An event grid topic provides a user-defined endpoint that you post your events to. The following example creates the custom topic in your resource group. Replace <topic_name> with a unique name for your topic. The topic name must be unique because it's represented by a DNS entry.

New-AzureRmEventGridTopic -ResourceGroupName gridResourceGroup -Location westus2 -Name <topic_name>

Create a message endpoint

Before subscribing to the custom topic, let's create the endpoint for the event message. Rather than write code to respond to the event, let's create an endpoint that collects the messages so you can view them. Hookbin is a third-party tool that enables you to create an endpoint, and view requests that are sent to it. Go to Hookbin and click Create New Endpoint. Copy the bin URL, because you need it when subscribing to the topic.

Subscribe to a topic

You subscribe to a topic to tell Event Grid which events you want to track. The following example subscribes to the custom topic you created, and passes the URL from Hookbin as the endpoint for event notification. Replace <event_subscription_name> with a unique name for your subscription, and <endpoint_URL> with the value from the preceding section. By specifying an endpoint when subscribing, Event Grid handles the routing of events to that endpoint. For <topic_name>, use the value you created earlier.

New-AzureRmEventGridSubscription -EventSubscriptionName <event_subscription_name> -Endpoint <endpoint_URL> -ResourceGroupName gridResourceGroup -TopicName <topic_name>

Send an event to your topic

Let's trigger an event to see how Event Grid distributes the message to your endpoint. First, let's get the URL and key for the topic. Again, use your topic name for <topic_name>.

$endpoint = (Get-AzureRmEventGridTopic -ResourceGroupName gridResourceGroup -Name <topic-name>).Endpoint
$keys = Get-AzureRmEventGridTopicKey -ResourceGroupName gridResourceGroup -Name <topic-name>

To simplify this article, let's set up sample event data to send to the custom topic. Typically, an application or Azure service would send the event data. The following example uses Hashtable to construct the event's data htbody and then coverts it to well-formed JSON payload object $body:

$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)+"]"

If you view $body, you see the full event. 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.

Now, send the event to your topic.

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

You've triggered the event, and Event Grid sent the message to the endpoint you configured when subscribing. Browse to the endpoint URL that you created earlier. Or, click refresh in your open browser. You see the event you just sent.

[{
  "id": "1807",
  "eventType": "recordInserted",
  "subject": "myapp/vehicles/motorcycles",
  "eventTime": "2018-01-25T15:58:13",
  "data": {
    "make": "Ducati",
    "model": "Monster"
  },
  "dataVersion": "1.0",
  "metadataVersion": "1",
  "topic": "/subscriptions/{subscription-id}/resourceGroups/{resource-group}/providers/Microsoft.EventGrid/topics/{topic}"
}]

Clean up resources

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

Remove-AzureRmResourceGroup -Name gridResourceGroup

Next steps

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