教程:使用托管标识创建自动化 PowerShell runbook

本教程会指导你在 Azure 自动化中创建一个使用托管标识(而不是运行方式帐户)与资源进行交互的 PowerShell runbook。 基于 Windows PowerShell 的 PowerShell Runbook。 借助 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 -Subscription -Environment AzureChinaCloud
    }
    
    # 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
    Disable-AzContextAutosave -Scope Process | Out-Null
    
    # Connect using a Managed Service Identity
    try {
            $AzureContext = (Connect-AzAccount -Identity -Environment AzureChinaCloud).context
        }
    catch{
            Write-Output "There is no system-assigned user identity. Aborting."; 
            exit
        }
    
    # set and store context
    $AzureContext = Set-AzContext -SubscriptionName $AzureContext.Subscription `
        -DefaultProfile $AzureContext
    
    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
            if ((Get-AzAutomationAccount -ResourceGroupName $resourceGroup `
                    -Name $automationAccount `
                    -DefaultProfile $AzureContext).Identity.UserAssignedIdentities.Values.PrincipalId.Contains($identity.PrincipalId))
                {
                    $AzureContext = (Connect-AzAccount -Identity -AccountId $identity.ClientId -Environment AzureChinaCloud).context
    
                    # set and store context
                    $AzureContext = Set-AzContext -SubscriptionName $AzureContext.Subscription -DefaultProfile $AzureContext
                }
            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 的信息,请参阅: