Share via


教學課程:使用 Azure CLI 將原則狀態變更事件路由至事件方格

在本文中,您將瞭解如何設定 Azure 原則事件訂用帳戶,來將原則狀態變更事件傳送至 web 端點。 Azure 原則使用者可以訂閱在資源上發生原則狀態變更時所發出的事件。 這些事件可以觸發 Web hook、Azure FunctionsAzure 儲存體佇列,或 Azure 事件方格所支援的任何其他事件處理常式。 通常,您會將事件傳送至可處理事件資料及採取行動的端點。 不過,若要簡化這份教學課程,您可將事件傳送至可收集及顯示訊息的 Web 應用程式。

必要條件

  • 如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶

  • 此快速入門需要您執行 Azure CLI 2.0.76 版或更新版本。 若要尋找版本,請執行 az --version。 如果您需要安裝或升級,請參閱安裝 Azure CLI

Azure Cloud Shell

Azure Cloud Shell 是裝載於 Azure 中的互動式殼層環境,可在瀏覽器中使用。 您可以使用 Bash 或 PowerShell 搭配 Cloud Shell,與 Azure 服務共同使用。 您可以使用 Cloud Shell 預先安裝的命令,執行本文提到的程式碼,而不必在本機環境上安裝任何工具。

要啟動 Azure Cloud Shell:

選項 範例/連結
選取程式碼或命令區塊右上角的 [試試看]。 選取 [試試看] 並不會自動將程式碼或命令複製到 Cloud Shell 中。 Screenshot that shows an example of Try It for Azure Cloud Shell.
請前往 https://shell.azure.com,或選取 [啟動 Cloud Shell] 按鈕,在瀏覽器中開啟 Cloud Shell。 Button to launch Azure Cloud Shell.
選取 Azure 入口網站右上方功能表列上的 [Cloud Shell] 按鈕。 Screenshot that shows the Cloud Shell button in the Azure portal

若要使用 Azure Cloud Shell:

  1. 啟動 Cloud Shell。

  2. 選取程式碼區塊 (或命令區塊) 上的 [複製] 按鈕以複製程式碼或命令。

  3. 透過在 Windows 和 Linux 上選取 Ctrl+Shift+V;或在 macOS 上選取 Cmd+Shift+V,將程式碼或命令貼到 Cloud Shell 工作階段中。

  4. 選取 Enter 鍵執行程式碼或命令。

建立資源群組

Event Grid 為 Azure 資源,必須放入 Azure 資源群組中。 資源群組是在其中部署與管理 Azure 資源的邏輯集合。

使用 az group create 命令來建立資源群組。

下列範例會在 westus <resource_group_name> 位置建立名為 的資源群組。 以資源群組的唯一名稱取代 <resource_group_name>

# Log in first with az login if you're not using Cloud Shell

az group create --name <resource_group_name> --location westus

建立事件方格系統主題

既然有資源群組,我們會建立系統主題。 事件方格中的系統主題代表 Azure 服務所發佈的一或多個事件,例如 Azure 原則和 Azure 事件中樞。 此系統主題會將 Microsoft.PolicyInsights.PolicyStates 主題類型用於 Azure 原則狀態變更。

首先,您必須在適當的管理範圍註冊 PolicyInsightsEventGrid 資源提供者 (RP)。 雖然 Azure 入口網站會自動註冊您第一次叫用的任何 RP,但 Azure CLI 不會。

# Log in first with az login if you're not using Cloud Shell

# Register the required RPs at the management group scope
az provider register --namespace Microsoft.PolicyInsights -m <managementGroupId>
az provider register --namespace Microsoft.EventGrid -m <managementGroupId>

# Alternatively, register the required RPs at the subscription scope (defaults to current subscription context)
az provider register --namespace Microsoft.PolicyInsights
az provider register --namespace Microsoft.EventGrid

接下來,將 scope 參數中的 <subscriptionId> 取代為您訂用帳戶的識別碼,並將 resource-group 參數中的 <resource_group_name> 取代為先前建立的資源群組。

az eventgrid system-topic create --name PolicyStateChanges --location global --topic-type Microsoft.PolicyInsights.PolicyStates --source "/subscriptions/<subscriptionId>" --resource-group "<resource_group_name>"

如果您的事件方格系統主題將套用至管理群組範圍,則 Azure CLI --source 參數語法會稍有不同。 以下是範例:

az eventgrid system-topic create --name PolicyStateChanges --location global --topic-type Microsoft.PolicyInsights.PolicyStates --source "/tenants/<tenantID>/providers/Microsoft.Management/managementGroups/<management_group_name>" --resource-group "<resource_group_name>"

建立訊息端點

訂閱主題之前,讓我們建立事件訊息的端點。 端點通常會根據事件資料來採取動作。 若要簡化此快速入門,請部署預先建置的 Web 應用程式以顯示事件訊息。 部署的解決方案包括 App Service 方案、App Service Web 應用程式,以及 GitHub 的原始程式碼。

以 Web 應用程式的唯一名稱取代 <your-site-name>。 Web 應用程式名稱必須是唯一的,因為它是 DNS 項目的一部分。

# Log in first with az login if you're not using Cloud Shell

az deployment group create \
  --resource-group <resource_group_name> \
  --template-uri "https://raw.githubusercontent.com/Azure-Samples/azure-event-grid-viewer/master/azuredeploy.json" \
  --parameters siteName=<your-site-name> hostingPlanName=viewerhost

部署需要幾分鐘的時間才能完成。 成功部署之後,檢視 Web 應用程式,確定它正在執行。 在網頁瀏覽器中,瀏覽至:https://<your-site-name>.azurewebsites.net

您現在應該會看到沒有顯示任何訊息的網站。

訂閱系統主題

您可訂閱主題,告知 Event Grid 您想要追蹤的事件,以及要將事件傳送至何處。 下列範例可訂閱您所建立的系統主題,從 Web 應用程式傳遞 URL 做為事件通知的接收端點。 以事件訂用帳戶的名稱來取代 <event_subscription_name>。 對於 <resource_group_name><your-site-name>,使用您稍早建立的值。

Web 應用程式的端點必須包含的尾碼 /api/updates/

# Log in first with az login if you're not using Cloud Shell

# Create the subscription
az eventgrid system-topic event-subscription create \
  --name <event_subscription_name> \
  --resource-group <resource_group_name> \
  --system-topic-name PolicyStateChanges \
  --endpoint https://<your-site-name>.azurewebsites.net/api/updates

再次檢視您的 Web 應用程式,並注意訂閱驗證事件是否已傳送至其中。 選取眼睛圖示以展開事件資料。 事件方格會傳送驗證事件,以便端點確認接收事件資料。 Web 應用程式包括用於驗證訂閱的程式碼。

Screenshot of the Event Grid subscription validation event in the pre-built web app.

建立原則指派

在本快速入門中,您會建立原則指派,並指派 [需要資源群組上的標籤] 定義。 此原則定義會識別資源群組,這些資源群組缺少原則指派期間所設定的標籤。

執行下列命令,以建立原則指派,其範圍限定在您建立以保存事件方格主題的資源群組:

# Log in first with az login if you're not using Cloud Shell

az policy assignment create --name 'requiredtags-events' --display-name 'Require tag on RG' --scope '<resourceGroupScope>' --policy '<policy definition ID>' --params '{ \"tagName\": { \"value\": \"EventTest\" } }'

上述命令會使用下列資訊:

  • Name - 指派的實際名稱。 在此範例中,使用了 requiredtags-events
  • DisplayName - 原則指派的顯示名稱。 在此案例下,您會在 RG 上使用 Require 標籤
  • 範圍 – 範圍會決定在哪些資源或資源群組上強制執行原則指派。 範圍從訂用帳戶到資源群組。 請務必將 <scope> 取代為您的資源群組。 資源群組範圍的格式為 /subscriptions/<subscriptionId>/resourceGroups/<resourceGroup>
  • 原則 - 原則定義識別碼,這是您用來建立指派的根基。 在此案例下,這是原則定義需要資源群組上的標籤的識別碼。 若要取得原則定義識別碼,請執行此命令:az policy definition list --query "[?displayName=='Require a tag on resource groups']"

建立原則指派之後,請等候 Microsoft.PolicyInsights.PolicyStateCreated 事件通知出現在 Web 應用程式中。 我們建立的資源群組會顯示要啟動的 NonCompliantdata.complianceState 值。

Screenshot of the Event Grid subscription Policy State Created event for the resource group in the pre-built web app.

注意

如果資源群組從訂用帳戶或管理群組階層繼承其他原則指派,也會顯示每個事件。 藉由評估 data.policyDefinitionId 屬性,確認事件適用於本教學課程中的指派。

在資源群組上觸發變更

若要讓資源群組符合規範,需要名稱為 EventTest 的標籤。 使用下列命令將標籤新增至資源群組,並以您的訂用帳戶識別碼取代 <subscriptionId>,並以資源群組名稱取代 <resourceGroup>

# Log in first with az login if you're not using Cloud Shell

az tag create --resource-id '/subscriptions/<SubscriptionID>/resourceGroups/<resourceGroup>' --tags EventTest=true

將必要的標籤新增至資源群組之後,請等候 Microsoft.PolicyInsights.PolicyStateChanged 事件通知出現在 Web 應用程式中。 展開事件,data.complianceState 值現在會顯示符合規範

疑難排解

如果您看到類似下列其中一項錯誤,請確保您已在您訂閱的範圍 (管理群組或訂用帳戶) 中註冊兩個資源提供者:

  • Deployment has failed with the following error: {"code":"Publisher Notification Error","message":"Failed to enable publisher notifications.","details":[{"code":"Publisher Provider Error","message":"GET request for <uri> failed with status code: Forbidden, code: AuthorizationFailed and message: The client '<identifier>' with object id '<identifier>' does not have authorization to perform action 'microsoft.policyinsights/eventGridFilters/read' over scope '<scope>/providers/microsoft.policyinsights/eventGridFilters/_default' or the scope is invalid. If access was recently granted, please refresh your credentials.."}]}
  • Deployment has failed with the following error: {'code':'Publisher Notification Error','message':'Failed to enable publisher notifications.','details':[{'code':'ApiVersionNotSupported','message':'Event Grid notifications are currently not supported by microsoft.policyinsights in global. Try re-registering Microsoft.EventGrid provider if this is your first event subscription in this region.'}]}

清除資源

如果您打算繼續使用此 web 應用程式和 Azure 原則事件訂用帳戶,請勿清除在本文中建立的資源。 如果您不打算繼續,請使用下列命令刪除您在本文建立的資源。

以您在上面建立的資源群組取代 <resource_group_name>

az group delete --name <resource_group_name>

下一步

您現在知道如何為 Azure 原則建立主題和事件訂用帳戶,請深入瞭解原則狀態變更事件以及 Event Grid 如何協助您: