教學課程:建立自動化 PowerShell Runbook 以使用受控識別

本教學課程會逐步引導您在 Azure 自動化中建立 PowerShell Runbook 以使用受控識別,而不是執行身分帳戶以與資源互動。 PowerShell Runbook 以 Windows PowerShell 為基礎。 Microsoft Entra ID 中的受控識別可讓您的 Runbook 輕鬆存取其他受 Microsoft Entra 保護的資源。

在本教學課程中,您會了解如何:

  • 將權限指派給受控識別
  • 建立 PowerShell Runbook

如果您沒有 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 = "resourceGroupName"
    
    # These values are used in this tutorial
    $automationAccount = "xAutomationAccount"
    $userAssignedManagedIdentity = "xUAMI"
    
  3. 使用 PowerShell cmdlet New-AzRoleAssignment 將角色指派給系統指派的受控識別。

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

    $UAMI = (Get-AzUserAssignedIdentity -ResourceGroupName $resourceGroup -Name $userAssignedManagedIdentity).PrincipalId
    New-AzRoleAssignment `
        -ObjectId $UAMI `
        -ResourceGroupName $resourceGroup `
        -RoleDefinitionName $role1
    
  5. 需要系統指派受控識別的其他權限,才能執行本教學課程中使用的 Cmdlet Get-AzUserAssignedIdentityGet-AzAutomationAccount

    $role2 = "Reader"
    New-AzRoleAssignment `
        -ObjectId $SAMI `
        -ResourceGroupName $resourceGroup `
        -RoleDefinitionName $role2
    

建立 PowerShell Runbook

建立 Runbook 以允許受控識別的執行。 Runbook 將啟動已停止的 VM,或停止執行中的 VM。

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

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

  3. 選取 [建立 Runbook]

    1. 將 Runbook 命名為 miTesting
    2. 從 [Runbook 類型] 下拉式清單中,選取 [PowerShell]
    3. 從 [執行階段版本] 下拉式清單中,選取 [7.1 (預覽)] 或 [5.1]
    4. 輸入適用的 [說明]
  4. 按一下 [建立] 以建立 Runbook。

  5. 在 Runbook 編輯器中,貼上下列程式碼:

    Param(
        [string]$ResourceGroup,
        [string]$VMName,
        [string]$Method,
        [string]$UAMI 
    )
    
    $automationAccount = "xAutomationAccount"
    
    # Ensures you do not inherit an AzContext in your runbook
    $null = Disable-AzContextAutosave -Scope Process
    
    # Connect using a Managed Service Identity
    try {
        $AzureConnection = (Connect-AzAccount -Identity).context
    }
    catch {
        Write-Output "There is no system-assigned user identity. Aborting." 
        exit
    }
    
    # set and store context
    $AzureContext = Set-AzContext -SubscriptionName $AzureConnection.Subscription -DefaultProfile $AzureConnection
    
    if ($Method -eq "SA") {
        Write-Output "Using system-assigned managed identity"
    }
    elseif ($Method -eq "UA") {
        Write-Output "Using user-assigned managed identity"
    
        # Connects using the Managed Service Identity of the named user-assigned managed identity
        $identity = Get-AzUserAssignedIdentity -ResourceGroupName $ResourceGroup -Name $UAMI -DefaultProfile $AzureContext
    
        # validates assignment only, not perms
        $AzAutomationAccount = Get-AzAutomationAccount -ResourceGroupName $ResourceGroup -Name $automationAccount -DefaultProfile $AzureContext
        if ($AzAutomationAccount.Identity.UserAssignedIdentities.Values.PrincipalId.Contains($identity.PrincipalId)) {
            $AzureConnection = (Connect-AzAccount -Identity -AccountId $identity.ClientId).context
    
            # set and store context
            $AzureContext = Set-AzContext -SubscriptionName $AzureConnection.Subscription -DefaultProfile $AzureConnection
        }
        else {
            Write-Output "Invalid or unassigned user-assigned managed identity"
            exit
        }
    }
    else {
        Write-Output "Invalid method. Choose UA or SA."
        exit
    }
    
    # Get current state of VM
    $status = (Get-AzVM -ResourceGroupName $ResourceGroup -Name $VMName -Status -DefaultProfile $AzureContext).Statuses[1].Code
    
    Write-Output "`r`n Beginning VM status: $status `r`n"
    
    # Start or stop VM based on current state
    if ($status -eq "Powerstate/deallocated") {
        Start-AzVM -Name $VMName -ResourceGroupName $ResourceGroup -DefaultProfile $AzureContext
    }
    elseif ($status -eq "Powerstate/running") {
        Stop-AzVM -Name $VMName -ResourceGroupName $ResourceGroup -DefaultProfile $AzureContext -Force
    }
    
    # Get new state of VM
    $status = (Get-AzVM -ResourceGroupName $ResourceGroup -Name $VMName -Status -DefaultProfile $AzureContext).Statuses[1].Code  
    
    Write-Output "`r`n Ending VM status: $status `r`n `r`n"
    
    Write-Output "Account ID of current context: " $AzureContext.Account.Id
    
  6. 在編輯器中,視需要修訂第 8 行的 $automationAccount 變數值。

  7. 選取 [儲存],然後選取 [測試] 窗格。

  8. 使用適當的值填入參數 RESOURCEGROUPVMNAME。 針對 METHOD 參數輸入 SA;針對 UAMI 參數輸入 xUAMI。 Runbook 將嘗試使用系統指派的受控識別來變更 VM 的電源狀態。

  9. 選取 [開始]。 完成 Runbook 後,輸出應顯示如下:

     Beginning VM status: PowerState/deallocated
    
    OperationId : 5b707401-f415-4268-9b43-be1f73ddc54b
    Status      : Succeeded
    StartTime   : 8/3/2021 10:52:09 PM
    EndTime     : 8/3/2021 10:52:50 PM
    Error       : 
    Name        : 
    
     Ending VM status: PowerState/running 
    
    Account ID of current context: 
    MSI@50342
    
  10. METHOD 參數的值變更為 UA

  11. 選取 [開始]。 Runbook 將嘗試使用具明使用者指派的受控識別來變更 VM 的電源狀態。 完成 Runbook 後,輸出應顯示如下:

    Using user-assigned managed identity
    
     Beginning VM status: PowerState/running 
    
    OperationId : 679fcadf-d0b9-406a-9282-66bc211a9fbf
    Status      : Succeeded
    StartTime   : 8/3/2021 11:06:03 PM
    EndTime     : 8/3/2021 11:06:49 PM
    Error       : 
    Name        : 
    
     Ending VM status: PowerState/deallocated 
    
    Account ID of current context: 
    9034f5d3-c46d-44d4-afd6-c78aeab837ea
    

清除資源

若要移除不再需要的資源,請執行下列 Runbook。

#Remove runbook
Remove-AzAutomationRunbook `
    -ResourceGroupName $resourceGroup `
    -AutomationAccountName $automationAccount `
    -Name "miTesting" `
    -Force

# Remove role assignments
Remove-AzRoleAssignment `
    -ObjectId $UAMI `
    -ResourceGroupName $resourceGroup `
    -RoleDefinitionName $role1

Remove-AzRoleAssignment `
    -ObjectId $SAMI `
    -ResourceGroupName $resourceGroup `
    -RoleDefinitionName $role2

Remove-AzRoleAssignment `
    -ObjectId $SAMI `
    -ResourceGroupName $resourceGroup `
    -RoleDefinitionName $role1

下一步

在本教學課程中,您已在 Azure 自動化中建立 PowerShell Runbook 以使用受控識別,而不是執行身分帳戶以與資源互動。 如需了解 PowerShell 工作流程 Runbook,請參閱: