筛选事件网格的事件Filter events for Event Grid

本文介绍如何在创建事件网格订阅时筛选事件。This article shows how to filter events when creating an Event Grid subscription. 若要了解事件筛选的选项,请参阅了解事件网格订阅的事件筛选To learn about the options for event filtering, see Understand event filtering for Event Grid subscriptions.

备注

本文进行了更新,以便使用新的 Azure PowerShell Az 模块。This article has been updated to use the new Azure PowerShell Az module. 你仍然可以使用 AzureRM 模块,至少在 2020 年 12 月之前,它将继续接收 bug 修补程序。You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. 若要详细了解新的 Az 模块和 AzureRM 兼容性,请参阅新 Azure Powershell Az 模块简介To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. 有关 Az 模块安装说明,请参阅安装 Azure PowerShellFor Az module installation instructions, see Install Azure PowerShell.

按事件类型筛选Filter by event type

创建事件网格订阅时,可以指定要发送到终结点的事件类型When creating an Event Grid subscription, you can specify which event types to send to the endpoint. 本部分中的示例创建资源组的事件订阅,但会限制发送到 Microsoft.Resources.ResourceWriteFailureMicrosoft.Resources.ResourceWriteSuccess 的事件。The examples in this section create event subscriptions for a resource group but limit the events that are sent to Microsoft.Resources.ResourceWriteFailure and Microsoft.Resources.ResourceWriteSuccess. 如果在按事件类型筛选事件时需要更多灵活性,请参阅按高级运算符和数据字段筛选。If you need more flexibility when filtering events by event types, see Filter by advanced operators and data fields.

对于 PowerShell,请在创建订阅时使用 -IncludedEventType 参数。For PowerShell, use the -IncludedEventType parameter when creating the subscription.

$includedEventTypes = "Microsoft.Resources.ResourceWriteFailure", "Microsoft.Resources.ResourceWriteSuccess"

New-AzEventGridSubscription `
  -EventSubscriptionName demoSubToResourceGroup `
  -ResourceGroupName myResourceGroup `
  -Endpoint <endpoint-URL> `
  -IncludedEventType $includedEventTypes

对于 Azure CLI,请使用 --included-event-types 参数。For Azure CLI, use the --included-event-types parameter. 以下示例在 Bash shell 中使用 Azure CLI:The following example uses Azure CLI in a Bash shell:

includedEventTypes="Microsoft.Resources.ResourceWriteFailure Microsoft.Resources.ResourceWriteSuccess"

az eventgrid event-subscription create \
  --name demoSubToResourceGroup \
  --source-resource-id <resouce-ID> \
  --endpoint <endpoint-URL> \
  --included-event-types $includedEventTypes

对于资源管理器模板,请使用 includedEventTypes 属性。For a Resource Manager template, use the includedEventTypes property.

"resources": [
  {
    "type": "Microsoft.EventGrid/eventSubscriptions",
    "name": "[parameters('eventSubName')]",
    "apiVersion": "2018-09-15-preview",
    "properties": {
      "destination": {
        "endpointType": "WebHook",
        "properties": {
          "endpointUrl": "[parameters('endpoint')]"
        }
      },
      "filter": {
        "subjectBeginsWith": "",
        "subjectEndsWith": "",
        "isSubjectCaseSensitive": false,
        "includedEventTypes": [
          "Microsoft.Resources.ResourceWriteFailure",
          "Microsoft.Resources.ResourceWriteSuccess"
        ]
      }
    }
  }
]

按主题筛选Filter by subject

可以按事件数据中的主题筛选事件。You can filter events by the subject in the event data. 可以指定一个值来匹配主题的开头或结尾。You can specify a value to match for the beginning or end of the subject. 如果在按主题筛选事件时需要更多灵活性,请参阅按高级运算符和数据字段筛选。If you need more flexibility when filtering events by subject, see Filter by advanced operators and data fields.

在以下 PowerShell 示例中,会创建一个按主题开头筛选的事件订阅。In the following PowerShell example, you create an event subscription that filters by the beginning of the subject. 使用 -SubjectBeginsWith 参数将事件限制为特定资源的事件。You use the -SubjectBeginsWith parameter to limit events to ones for a specific resource. 然后传递网络安全组的资源 ID。You pass the resource ID of a network security group.

$resourceId = (Get-AzResource -ResourceName demoSecurityGroup -ResourceGroupName myResourceGroup).ResourceId

New-AzEventGridSubscription `
  -Endpoint <endpoint-URL> `
  -EventSubscriptionName demoSubscriptionToResourceGroup `
  -ResourceGroupName myResourceGroup `
  -SubjectBeginsWith $resourceId

下一个 PowerShell 示例创建 blob 存储的订阅。The next PowerShell example creates a subscription for a blob storage. 其中将事件限制为主题以 .jpg 结尾的事件。It limits events to ones with a subject that ends in .jpg.

$storageId = (Get-AzStorageAccount -ResourceGroupName myResourceGroup -AccountName $storageName).Id

New-AzEventGridSubscription `
  -EventSubscriptionName demoSubToStorage `
  -Endpoint <endpoint-URL> `
  -ResourceId $storageId `
  -SubjectEndsWith ".jpg"

在以下 Azure CLI 示例中,会创建一个按主题开头筛选的事件订阅。In the following Azure CLI example, you create an event subscription that filters by the beginning of the subject. 使用 --subject-begins-with 参数将事件限制为特定资源的事件。You use the --subject-begins-with parameter to limit events to ones for a specific resource. 然后传递网络安全组的资源 ID。You pass the resource ID of a network security group.

resourceId=$(az resource show --name demoSecurityGroup --resource-group myResourceGroup --resource-type Microsoft.Network/networkSecurityGroups --query id --output tsv)

az eventgrid event-subscription create \
  --name demoSubscriptionToResourceGroup \
  --source-resource-id <resouce-ID> \
  --endpoint <endpoint-URL> \
  --subject-begins-with $resourceId

下一个 Azure CLI 示例创建 blob 存储的订阅。The next Azure CLI example creates a subscription for a blob storage. 其中将事件限制为主题以 .jpg 结尾的事件。It limits events to ones with a subject that ends in .jpg.

storageid=$(az storage account show --name $storageName --resource-group myResourceGroup --query id --output tsv)

az eventgrid event-subscription create \
  --resource-id $storageid \
  --name demoSubToStorage \
  --endpoint <endpoint-URL> \
  --subject-ends-with ".jpg"

在以下资源管理器模板示例中,会创建一个按主题开头筛选的事件订阅。In the following Resource Manager template example, you create an event subscription that filters by the beginning of the subject. 使用 subjectBeginsWith 属性将事件限制为特定资源的事件。You use the subjectBeginsWith property to limit events to ones for a specific resource. 然后传递网络安全组的资源 ID。You pass the resource ID of a network security group.

"resources": [
  {
    "type": "Microsoft.EventGrid/eventSubscriptions",
    "name": "[parameters('eventSubName')]",
    "apiVersion": "2018-09-15-preview",
    "properties": {
      "destination": {
        "endpointType": "WebHook",
        "properties": {
          "endpointUrl": "[parameters('endpoint')]"
        }
      },
      "filter": {
        "subjectBeginsWith": "[resourceId('Microsoft.Network/networkSecurityGroups','demoSecurityGroup')]",
        "subjectEndsWith": "",
        "isSubjectCaseSensitive": false,
        "includedEventTypes": [ "All" ]
      }
    }
  }
]

下一个资源管理模板示例创建 blob 存储的订阅。The next Resource Manager template example creates a subscription for a blob storage. 其中将事件限制为主题以 .jpg 结尾的事件。It limits events to ones with a subject that ends in .jpg.

"resources": [
  {
    "type": "Microsoft.Storage/storageAccounts/providers/eventSubscriptions",
    "name": "[concat(parameters('storageName'), '/Microsoft.EventGrid/', parameters('eventSubName'))]",
    "apiVersion": "2018-09-15-preview",
    "properties": {
      "destination": {
        "endpointType": "WebHook",
        "properties": {
          "endpointUrl": "[parameters('endpoint')]"
        }
      },
      "filter": {
        "subjectEndsWith": ".jpg",
        "subjectBeginsWith": "",
        "isSubjectCaseSensitive": false,
        "includedEventTypes": [ "All" ]
      }
    }
  }
]

按运算符和数据进行筛选Filter by operators and data

为提高筛选灵活性,可以使用运算符和数据属性来筛选事件。For more flexibility in filtering, you can use operators and data properties to filter events.

订阅高级筛选器Subscribe with advanced filters

若要了解可用于高级筛选的运算符和密钥,请参阅高级筛选To learn about the operators and keys that you can use for advanced filtering, see Advanced filtering.

这些示例创建自定义主题。These examples create a custom topic. 它们订阅自定义主题,并按数据对象中的值进行筛选。They subscribe to the custom topic and filter by a value in the data object. 将颜色属性设置为“蓝色”、“红色”或“绿色”的事件会发送到订阅。Events that have the color property set to blue, red, or green are sent to the subscription.

对于 Azure CLI,请使用:For Azure CLI, use:

topicName=<your-topic-name>
endpointURL=<endpoint-URL>

az group create -n gridResourceGroup -l chinaeast2
az eventgrid topic create --name $topicName -l chinaeast2 -g gridResourceGroup

topicid=$(az eventgrid topic show --name $topicName -g gridResourceGroup --query id --output tsv)

az eventgrid event-subscription create \
  --source-resource-id $topicid \
  -n demoAdvancedSub \
  --advanced-filter data.color stringin blue red green \
  --endpoint $endpointURL \
  --expiration-date "<yyyy-mm-dd>"

请注意为订阅设置到期日期Notice that an expiration date is set for the subscription.

对于 PowerShell,请使用:For PowerShell, use:

$topicName = <your-topic-name>
$endpointURL = <endpoint-URL>

New-AzResourceGroup -Name gridResourceGroup -Location chinaeast2
New-AzEventGridTopic -ResourceGroupName gridResourceGroup -Location chinaeast2 -Name $topicName

$topicid = (Get-AzEventGridTopic -ResourceGroupName gridResourceGroup -Name $topicName).Id

$expDate = '<mm/dd/yyyy hh:mm:ss>' | Get-Date
$AdvFilter1=@{operator="StringIn"; key="Data.color"; Values=@('blue', 'red', 'green')}

New-AzEventGridSubscription `
  -ResourceId $topicid `
  -EventSubscriptionName <event_subscription_name> `
  -Endpoint $endpointURL `
  -ExpirationDate $expDate `
  -AdvancedFilter @($AdvFilter1)

测试筛选器Test filter

若要测试筛选器,请发送将颜色字段设置为“绿色”的事件。To test the filter, send an event with the color field set to green. 由于绿色是筛选器中的值之一,因此该事件将传递到终结点。Because green is one of the values in the filter, the event is delivered to the endpoint.

对于 Azure CLI,请使用:For Azure CLI, use:

topicEndpoint=$(az eventgrid topic show --name $topicName -g gridResourceGroup --query "endpoint" --output tsv)
key=$(az eventgrid topic key list --name $topicName -g gridResourceGroup --query "key1" --output tsv)

event='[ {"id": "'"$RANDOM"'", "eventType": "recordInserted", "subject": "myapp/vehicles/cars", "eventTime": "'`date +%Y-%m-%dT%H:%M:%S%z`'", "data":{ "model": "SUV", "color": "green"},"dataVersion": "1.0"} ]'

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

对于 PowerShell,请使用:For PowerShell, use:

$endpoint = (Get-AzEventGridTopic -ResourceGroupName gridResourceGroup -Name $topicName).Endpoint
$keys = Get-AzEventGridTopicKey -ResourceGroupName gridResourceGroup -Name $topicName

$eventID = Get-Random 99999
$eventDate = Get-Date -Format s

$htbody = @{
    id= $eventID
    eventType="recordInserted"
    subject="myapp/vehicles/cars"
    eventTime= $eventDate
    data= @{
        model="SUV"
        color="green"
    }
    dataVersion="1.0"
}

$body = "["+(ConvertTo-Json $htbody)+"]"

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

若要测试未发送事件的情形,请发送将颜色字段设置为“黄色”的事件。To test a scenario where the event isn't sent, send an event with the color field set to yellow. “黄色”不是订阅中所指定的其中一个值,因此不会将事件发送到订阅。Yellow isn't one of the values specified in the subscription, so the event isn't delivered to your subscription.

对于 Azure CLI,请使用:For Azure CLI, use:

event='[ {"id": "'"$RANDOM"'", "eventType": "recordInserted", "subject": "myapp/vehicles/cars", "eventTime": "'`date +%Y-%m-%dT%H:%M:%S%z`'", "data":{ "model": "SUV", "color": "yellow"},"dataVersion": "1.0"} ]'

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

对于 PowerShell,请使用:For PowerShell, use:

$htbody = @{
    id= $eventID
    eventType="recordInserted"
    subject="myapp/vehicles/cars"
    eventTime= $eventDate
    data= @{
        model="SUV"
        color="yellow"
    }
    dataVersion="1.0"
}

$body = "["+(ConvertTo-Json $htbody)+"]"

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

后续步骤Next steps