Подписка на события группы ресурсов и фильтрация по ресурсу с использованием PowerShell

С помощью этого скрипта в службе "Сетка событий" создается подписка на события, связанные с группой ресурсов. Он использует фильтр, чтобы получить события для указанного ресурса в группе ресурсов.

Если у вас еще нет подписки Azure, создайте бесплатную учетную запись Azure, прежде чем начинать работу.

Пример скрипта — стабильная версия

Примечание.

Мы рекомендуем использовать модуль Azure Az PowerShell для взаимодействия с Azure. Чтобы начать работу, см. статью Установка Azure PowerShell. Дополнительные сведения см. в статье Перенос Azure PowerShell с AzureRM на Az.

# Provide an endpoint for handling the events. Must be formatted "https://your-endpoint-URL"
$myEndpoint = "<your-endpoint-URL>"

# Provide the name of the resource group to create. It will contain the network security group.
# You will subscribe to events for this resource group.
$myResourceGroup = "<resource-group-name>"

# Provide a name for the network security group to create.
$nsgName = "<your-nsg-name>"

# Create the resource group
New-AzResourceGroup -Name $myResourceGroup -Location westus2

# Create a network security group. You will filter events to only those that are related to this resource.
New-AzNetworkSecurityGroup -Name $nsgName -ResourceGroupName $myResourceGroup  -Location westus2

# Get the resource ID to filter events. The name of the network security group must not be the same as the other resource names.
$resourceId = (Get-AzResource -ResourceName $nsgName -ResourceGroupName $myResourceGroup).ResourceId

# Subscribe to the resource group. Provide the name of the resource group you want to subscribe to.
New-AzEventGridSubscription `
  -Endpoint $myEndpoint `
  -EventSubscriptionName demoSubscriptionToResourceGroup `
  -ResourceGroupName $myResourceGroup `
  -SubjectBeginsWith $resourceId

Пример скрипта — модуль предварительной версии

Важно!

Для использования этой функции Azure в PowerShell требуется установленный модуль AzureRM. Это устаревший модуль, поддерживаемый только в Windows PowerShell 5.1.x, в который больше не добавляются новые функции. Модули Az и AzureRM являются несовместимыми при использовании с одинаковыми версиями PowerShell. Если вам необходимы обе версии, выполните следующее:

  1. Удалите модуль Az в сеансе PowerShell 5.1.
  2. Установите модуль AzureRM в сеансе PowerShell 5.1.
  3. Скачайте и установите PowerShell Core 6.x или последующей версии.
  4. Установите модуль Az в сеансе PowerShell Core.

Для примера скрипта предварительной версии требуется модуль службы "Сетка событий". Чтобы установить его, выполните такую команду. Install-Module -Name AzureRM.EventGrid -AllowPrerelease -Force -Repository PSGallery

# You must have the latest version of the Event Grid PowerShell module.
# To install:
# Install-Module -Name AzureRM.EventGrid -AllowPrerelease -Force -Repository PSGallery

# Provide an endpoint for handling the events. Must be formatted "https://your-endpoint-URL"
$myEndpoint = "<your-endpoint-URL>"

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

# Provide the name of the resource group to create. It will contain the custom topic.
$myResourceGroup= "<resource-group-name>"

# Create the resource group
New-AzResourceGroup -Name $myResourceGroup -Location westus2

# Create custom topic
New-AzEventGridTopic -ResourceGroupName $myResourceGroup -Location westus2 -Name $topicName

# Get resource ID of custom topic
$topicid = (Get-AzEventGridTopic -ResourceGroupName $myResourceGroup -Name $topicName).Id

# Set the operator type, field and values for the filtering
$AdvFilter1=@{operator="StringIn"; key="Data.color"; Values=@('blue', 'red', 'green')}

# Subscribe to the custom topic. Filter based on a value in the event data.
New-AzEventGridSubscription `
  -ResourceId $topicid `
  -EventSubscriptionName demoSubWithFilter `
  -Endpoint $myEndpoint `
  -AdvancedFilter @($AdvFilter1)

Описание скрипта

Чтобы создать подписку на события, в скрипте используются указанные ниже команды. Для каждой команды в таблице приведены ссылки на соответствующую документацию.

Команда Примечания.
New-AzEventGridSubscription Создайте подписку в службе "Сетка событий".

Следующие шаги