Subscribe to events for a custom topic with Azure CLI

This script creates an Event Grid subscription to the events for a custom topic.

To run this sample, install the latest version of the Azure CLI. To start, run az login to create a connection with Azure.

Samples for the Azure CLI are written for the bash shell. To run this sample in Windows PowerShell or Command Prompt, you may need to change elements of the script.

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

The preview sample script requires the Event Grid extension. To install, run az extension add --name eventgrid.

Sample script - stable

#!/bin/bash

# Provide the name of the topic you are subscribing to
myTopic=demoContosoTopic

# Provide the name of the resource group containing the custom topic
resourceGroup=demoResourceGroup

# Provide an endpoint for handling the events.
myEndpoint="<endpoint URL>"

# Select the Azure subscription that contains the custom topic.
az account set --subscription "<name or ID of the subscription>"

# Subscribe to the custom event. Include the resource group that contains the custom topic.
az eventgrid event-subscription create \
  --resource-group $resourceGroup \
  --topic-name $myTopic  \
  --name demoSubscription \
  --endpoint $myEndpoint

Sample script - preview extension

#!/bin/bash

# You must have the latest version of the Event Grid preview extension.
# If you have not installed previously:
# az extension add -n eventgrid
# If you have installed previously:
# az extension update -n eventgrid

# Provide the name of the topic you are subscribing to
myTopic=demoContosoTopic

# Provide the name of the resource group containing the custom topic
resourceGroup=demoResourceGroup

# Provide an endpoint for handling the events.
myEndpoint="<endpoint URL>"

# Select the Azure subscription that contains the custom topic.
az account set --subscription "<name or ID of the subscription>"

# Get the resource ID of the custom topic
topicID=$(az eventgrid topic show --name $myTopic -g $resourceGroup --query id --output tsv)

# Subscribe to the custom event. Include the resource group that contains the custom topic.
az eventgrid event-subscription create \
  --source-resource-id $topicID \
  --name demoSubscription \
  --endpoint $myEndpoint

Script explanation

This script uses the following command to create the event subscription. Each command in the table links to command-specific documentation.

Command Notes
az eventgrid event-subscription create Create an Event Grid subscription.
az eventgrid event-subscription create - extension version Create an Event Grid subscription.

Next steps