使用警示來觸發 Azure 自動化 Runbook

您可以使用 Azure 監視器來監視 Azure 中大多數服務的基準層級計量和記錄。 您可以使用動作群組來呼叫 Azure 自動化 Runbook,以根據警示來自動執行工作。 本文示範如何使用警示來設定及執行 Runbook。

必要條件

警示類型

您可以將自動化 Runbook 與三種警示類型搭配使用:

  • 常見警示
  • 活動記錄警示 \(部分機器翻譯\)
  • 近乎即時的計量警示

注意

通用警示結構描述會將 Azure 中警示通知的使用量體驗標準化。 在過去,Azure 中的三個警示類型 (計量、記錄和活動記錄) 都有自己的電子郵件範本、Webhook 結構描述等等。若要深入了解,請參閱一般警示結構描述

當警示呼叫 Runbook 時,實際的呼叫是對 Webhook 的 HTTP POST 要求。 POST 要求的本文包含 JSON 格式的物件,其中具有與警示相關的實用屬性。 下表列出每種警示類型的承載結構描述連結:

Alert 描述 承載結構描述
一般警示 將 Azure 中警示通知耗用量體驗標準化的一般警示結構描述。 一般警示承載結構描述。
活動記錄警示 當 Azure 活動記錄中的任何新事件符合特定條件時,便傳送通知。 例如,當 myProductionResourceGroup 中發生 Delete VM 作業時,或出現狀態為 [作用中] 的新「Azure 服務健康狀態」事件時。 活動記錄警示承載結構描述
近乎即時計量警示 當一或多個平台層級的計量符合指定的條件時,便以比計量警示快的速度傳送通知。 例如,當在過去 5 分鐘 VM 上 [CPU %] 的值大於 90,且 [網路輸入] 的值大於 500 MB 時。 近乎即時計量警示承載結構描述

由於每種類型的警示所提供的資料不同,因此每種警示類型的處理方式也不同。 在下一節中,您將了解如何建立 Runbook 來處理不同類型的警示。

將權限指派給受控識別

將權限指派給適當的受控識別,以允許其停止虛擬機器。 Runbook 可以使用自動化帳戶的系統指派受控識別或使用者指派的受控識別。 本文提供了將權限指派給每個身分識別的步驟。 下列步驟會使用 PowerShell。 如果您比較想使用入口網站,請參閱使用 Azure 入口網站指派 Azure 角色

  1. 使用 Connect-AzAccount cmdlet 以互動方式登入 Azure 並遵循指示。

    # Sign in to your Azure subscription
    $sub = Get-AzSubscription -ErrorAction SilentlyContinue
    if(-not($sub))
    {
        Connect-AzAccount
    }
    
    # If you have multiple subscriptions, set the one to use
    # Select-AzSubscription -SubscriptionId <SUBSCRIPTIONID>
    
  2. 為下列變數提供適當的值,然後執行指令碼。

    $resourceGroup = "resourceGroup"
    $automationAccount = "AutomationAccount"
    $userAssignedManagedIdentity = "userAssignedManagedIdentity"
    
  3. 使用 PowerShell cmdlet New-AzRoleAssignment 將角色指派給系統指派的受控識別。

    $SAMI = (Get-AzAutomationAccount -ResourceGroupName $resourceGroup -Name $automationAccount).Identity.PrincipalId
    New-AzRoleAssignment `
        -ObjectId $SAMI `
        -ResourceGroupName $resourceGroup `
        -RoleDefinitionName "DevTest Labs User"
    
  4. 對使用者指派的受控識別指派角色。

    $UAMI = (Get-AzUserAssignedIdentity -ResourceGroupName $resourceGroup -Name $userAssignedManagedIdentity)
    New-AzRoleAssignment `
        -ObjectId $UAMI.PrincipalId `
        -ResourceGroupName $resourceGroup `
        -RoleDefinitionName "DevTest Labs User"
    
  5. 針對系統指派的受控識別,顯示 ClientId 並記錄其值以供稍後使用。

    $UAMI.ClientId
    

建立 Runbook 來處理警示

若要搭配警示使用「自動化」,您需要 Runbook 來管理傳遞給 Runbook 的警示 JSON 承載。 下列範例 Runbook 必須從 Azure 警示呼叫。

如上一節所述,每種類型的警示都有不同的結構描述。 指令碼會從警示採用 WebhookData Runbook 輸入參數中的 Webhook 資料。 接著,指令碼會評估 JSON 承載,以判斷使用的是哪種警示類型。

此範例會使用來自 Azure 虛擬機器 (VM) 的警示。 它會從承載擷取 VM 資料,然後使用該資訊來停止 VM。 您必須在執行 Runbook 的「自動化」帳戶中設定連線。 使用警示來觸發 Runbook 時,請務必檢查所觸發 Runbook 中的警示狀態。 每一次警示變更狀態時,Runbook 都會觸發。 警示有多個狀態,其中兩個最常見的是「已啟用」和「已解決」。 在 Runbook 邏輯中檢查狀態,以確保 Runbook 不會執行多次。 本文中的範例只會示範如何尋找狀態為「已啟用」的警示。

Runbook 會使用自動化帳戶系統指派的受控識別向 Azure 進行驗證,以針對 VM 執行管理動作。 Runbook 可以輕鬆地修改為使用使用者指派的受控識別。

注意

建議您使用公用網路存取,因為當自動化帳戶使用私人連結並設定 [公用存取] 設為 [停用] 時,無法使用 Azure 警示 (計量、記錄和活動記錄) 來觸發自動化 Webhook。

請使用此範例來建立名為 Stop-AzureVmInResponsetoVMAlert 的 Runbook。 您可以修改 PowerShell 指令碼,然後將它與許多不同的資源搭配使用。

  1. 登入 Azure 入口網站,然後瀏覽至您的自動化帳戶。

  2. 在 [程序自動化] 下方,選取 [Runbook]

  3. 選取 [+ 建立 Runbook]

    1. 將 Runbook 命名為 Stop-AzureVmInResponsetoVMAlert
    2. 從 [Runbook 類型] 下拉式清單中,選取 [PowerShell]
    3. 選取 建立
  4. 在 Runbook 編輯器中,貼上下列程式碼:

    [OutputType("PSAzureOperationResponse")]
    param
    (
        [Parameter (Mandatory=$false)]
        [object] $WebhookData
    )
    $ErrorActionPreference = "stop"
    
    if ($WebhookData)
    {
        # Get the data object from WebhookData
        $WebhookBody = (ConvertFrom-Json -InputObject $WebhookData.RequestBody)
    
        # Get the info needed to identify the VM (depends on the payload schema)
        $schemaId = $WebhookBody.schemaId
        Write-Verbose "schemaId: $schemaId" -Verbose
        if ($schemaId -eq "azureMonitorCommonAlertSchema") {
            # This is the common Metric Alert schema (released March 2019)
            $Essentials = [object] ($WebhookBody.data).essentials
            # Get the first target only as this script doesn't handle multiple
            $alertTargetIdArray = (($Essentials.alertTargetIds)[0]).Split("/")
            $SubId = ($alertTargetIdArray)[2]
            $ResourceGroupName = ($alertTargetIdArray)[4]
            $ResourceType = ($alertTargetIdArray)[6] + "/" + ($alertTargetIdArray)[7]
            $ResourceName = ($alertTargetIdArray)[-1]
            $status = $Essentials.monitorCondition
        }
        elseif ($schemaId -eq "AzureMonitorMetricAlert") {
            # This is the near-real-time Metric Alert schema
            $AlertContext = [object] ($WebhookBody.data).context
            $SubId = $AlertContext.subscriptionId
            $ResourceGroupName = $AlertContext.resourceGroupName
            $ResourceType = $AlertContext.resourceType
            $ResourceName = $AlertContext.resourceName
            $status = ($WebhookBody.data).status
        }
        elseif ($schemaId -eq "Microsoft.Insights/activityLogs") {
            # This is the Activity Log Alert schema
            $AlertContext = [object] (($WebhookBody.data).context).activityLog
            $SubId = $AlertContext.subscriptionId
            $ResourceGroupName = $AlertContext.resourceGroupName
            $ResourceType = $AlertContext.resourceType
            $ResourceName = (($AlertContext.resourceId).Split("/"))[-1]
            $status = ($WebhookBody.data).status
        }
        elseif ($schemaId -eq $null) {
            # This is the original Metric Alert schema
            $AlertContext = [object] $WebhookBody.context
            $SubId = $AlertContext.subscriptionId
            $ResourceGroupName = $AlertContext.resourceGroupName
            $ResourceType = $AlertContext.resourceType
            $ResourceName = $AlertContext.resourceName
            $status = $WebhookBody.status
        }
        else {
            # Schema not supported
            Write-Error "The alert data schema - $schemaId - is not supported."
        }
    
        Write-Verbose "status: $status" -Verbose
        if (($status -eq "Activated") -or ($status -eq "Fired"))
        {
            Write-Verbose "resourceType: $ResourceType" -Verbose
            Write-Verbose "resourceName: $ResourceName" -Verbose
            Write-Verbose "resourceGroupName: $ResourceGroupName" -Verbose
            Write-Verbose "subscriptionId: $SubId" -Verbose
    
            # Determine code path depending on the resourceType
            if ($ResourceType -eq "Microsoft.Compute/virtualMachines")
            {
                # This is an Resource Manager VM
                Write-Verbose "This is an Resource Manager VM." -Verbose
    
                # Ensures you do not inherit an AzContext in your runbook
                Disable-AzContextAutosave -Scope Process
    
                # Connect to Azure with system-assigned managed identity
                $AzureContext = (Connect-AzAccount -Identity).context
    
                # set and store context
                $AzureContext = Set-AzContext -SubscriptionName $AzureContext.Subscription -DefaultProfile $AzureContext
    
                # Stop the Resource Manager VM
                Write-Verbose "Stopping the VM - $ResourceName - in resource group - $ResourceGroupName -" -Verbose
                Stop-AzVM -Name $ResourceName -ResourceGroupName $ResourceGroupName -DefaultProfile $AzureContext -Force
                # [OutputType(PSAzureOperationResponse")]
            }
            else {
                # ResourceType not supported
                Write-Error "$ResourceType is not a supported resource type for this runbook."
            }
        }
        else {
            # The alert status was not 'Activated' or 'Fired' so no action taken
            Write-Verbose ("No action taken. Alert status: " + $status) -Verbose
        }
    }
    else {
        # Error
        Write-Error "This runbook is meant to be started from an Azure alert webhook only."
    }
    
  5. 如果您想要 Runbook 以系統指派的受控識別來執行,請將程式碼保持原狀。 如果您偏好使用使用者指派的受控識別,則:

    1. 從第 78 行移除 $AzureContext = (Connect-AzAccount -Identity).context
    2. 將其取代為 $AzureContext = (Connect-AzAccount -Identity -AccountId <ClientId>).context,然後
    3. 輸入您稍早取得的 [用戶端識別碼]。
  6. 選取 [儲存]、[發佈],然後在出現提示時選取 [是]

  7. 關閉 [Runbook] 頁面以返回 [自動化帳戶] 頁面。

建立警示

警示會使用動作群組,這是警示所觸發動作的集合。 Runbook 只是可與動作群組搭配使用的眾多動作之一。

  1. 在您的自動化帳戶中,在 [監視] 底下,選取 [警示]

  2. 選取 [+ 新增警示規則] 以開啟 [建立警示規則] 頁面。

    The create alert rule page and subsections.

  3. 在 [範圍] 下,選取 [編輯資源]

  4. 在 [選取資源] 頁面上,從 [依資源類型篩選] 下拉式清單中選取 [虛擬機器]

  5. 核取要監視的虛擬機器旁的方塊。 然後選取 [完成] 以返回 [建立警示規則] 頁面。

  6. 在 [條件] 下,選取 [新增條件]

  7. 在 [選取訊號] 頁面上,於搜尋文字方塊中輸入 Percentage CPU,然後從結果中選取 [CPU 百分比]

  8. 在 [設定訊號邏輯] 頁面上,於 [閾值] 下輸入初始下限值以供測試之用,例如 5。 確認警示如預期般運作後,便可返回並更新此值。 然後選取 [完成] 以返回 [建立警示規則] 頁面。

    Entering CPU percentage threshold value.

  9. 在 [動作] 底下,選取 [新增動作群組],然後選取 [+建立動作群組]

    The create action group page with Basics tab open.

  10. 在 [建立動作群組] 頁面上:

    1. 在 [基本資料] 索引標籤上,輸入 [動作群組名稱] 和 [顯示名稱]

    2. 在 [動作] 索引標籤的 [名稱] 文字方塊中,輸入名稱。 然後,從 [動作類型] 下拉式清單中,選取 [自動化 Runbook] 以開啟 [設定 Runbook] 頁面。

      1. 針對 [Runbook 來源] 項目,選取 [使用者]

      2. 從 [訂用帳戶] 下拉式清單中,選取您的訂用帳戶。

      3. 從 [自動化帳戶] 下拉式清單中,選取您的自動化帳戶。

      4. 從 [Runbook] 下拉式清單中,選取 [Stop-AzureVmInResponsetoVMAlert]

      5. 針對 [啟用一般警示結構描述] 項目,選取 [是]

      6. 選取 [確定] 以返回 [建立動作群組] 頁面。

        Configure runbook page with values.

    3. 選取 [檢閱 + 建立],然後選取 [建立] 以返回 [建立警示規則] 頁面。

  11. 在 [警示規則詳細資料] 底下,針對 [警示規則名稱] 文字方塊。

  12. 選取 [建立警示規則]。 您可以在所建立的活動記錄警示近乎即時警示中使用動作群組。

驗證

確定您的 VM 正在執行。 瀏覽至 Runbook 的 [Stop-AzureVmInResponsetoVMAlert],並監看要填入的 [最近的作業] 清單。 完成的作業出現之後,請選取作業並檢閱輸出。 另請檢查 VM 是否已停止。

Showing output from job.

常見的 Azure VM 管理作業

Azure 自動化會為常見的 Azure VM 管理作業提供指令碼,例如重新啟動 VM、停止 VM、刪除 VM、在 Runbook 資源庫中擴大和縮小案例。 這些指令碼也可以在 Azure 自動化的 GitHub 存放庫中找到。您也可以依照上述步驟所述來使用這些指令碼。

Azure VM 管理作業 詳細資料
Stop-Azure-VM-On-Alert 此 Runbook 會停止 Azure Resource Manager VM,以回應 Azure 警示觸發程序。

輸入是警示資料,其中包含要識別該停止的 VM 所需的資訊。

必須透過 Webhook 從 Azure 警示呼叫 Runbook。

應該將最新版的 Az 模組新增到自動化帳戶。

應該啟用受控識別,並應提供自動化帳戶的參與者存取權。
Restart-Azure-VM-On-Alert 此 Runbook 會停止 Azure Resource Manager VM,以回應 Azure 警示觸發程序。

輸入是警示資料,其中包含要識別該停止的 VM 所需的資訊。

必須透過 Webhook 從 Azure 警示呼叫 Runbook。

應該將最新版的 Az 模組新增到自動化帳戶。

應該啟用受控識別,並應提供自動化帳戶的參與者存取權。
Delete-Azure-VM-On-Alert 此 Runbook 會停止 Azure Resource Manager VM,以回應 Azure 警示觸發程序。

輸入是警示資料,其中包含要識別該停止的 VM 所需的資訊。

必須透過 Webhook 從 Azure 警示呼叫 Runbook。

應該將最新版的 Az 模組新增到自動化帳戶。

應該啟用受控識別,並應提供自動化帳戶的參與者存取權。
ScaleDown-Azure-VM-On-Alert 此 Runbook 會停止 Azure Resource Manager VM,以回應 Azure 警示觸發程序。

輸入是警示資料,其中包含要識別該停止的 VM 所需的資訊。

必須透過 Webhook 從 Azure 警示呼叫 Runbook。

應該將最新版的 Az 模組新增到自動化帳戶。

應該啟用受控識別,並應提供自動化帳戶的參與者存取權。
ScaleUp-Azure-VM-On-Alert 此 Runbook 會停止 Azure Resource Manager VM,以回應 Azure 警示觸發程序。

輸入是警示資料,其中包含要識別該停止的 VM 所需的資訊。

必須透過 Webhook 從 Azure 警示呼叫 Runbook。

應該將最新版的 Az 模組新增到自動化帳戶。

應該啟用受控識別,並應提供自動化帳戶的參與者存取權。

下一步