Subscribe to events for a resource group and filter for a resource with Azure CLI

This script creates an Event Grid subscription to the events for a resource group. It uses a filter to get only events for a specified resource in the resource group.

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 an Azure 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 an endpoint for handling the events.
myEndpoint="<endpoint URL>"

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

# Get the resource ID to filter events
resourceId=$(az resource show --name demoSecurityGroup --resource-group myResourceGroup --resource-type Microsoft.Network/networkSecurityGroups --query id --output tsv)

# Subscribe to the resource group. Provide the name of the resource group you want to subscribe to.
az eventgrid event-subscription create \
  --name demoSubscriptionToResourceGroup \
  --resource-group myResourceGroup \
  --endpoint $myEndpoint \
  --subject-begins-with $resourceId

Sample script - preview extension

#!/bin/bash

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

# Provide the name of the custom topic to create
topicName=<your-topic-name>

# Provide the name of the resource group to contain the custom topic
myResourceGroup=demoResourceGroup

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

# Create the resource group
az group create -n $myResourceGroup -l eastus2

# Create custom topic
az eventgrid topic create --name $topicName -l eastus2 -g $myResourceGroup

# Get resource ID of custom topic
topicid=$(az eventgrid topic show --name $topicName -g $myResourceGroup --query id --output tsv)

# Subscribe to the custom topic. Filter based on a value in the event data.
az eventgrid event-subscription create \
  --source-resource-id $topicid \
  -n demoAdvancedFilterSub \
  --advanced-filter data.color stringin blue red green \
  --endpoint $endpointURL

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