자습서: 관리 ID를 사용하여 Automation PowerShell Runbook 만들기

이 자습서에서는 Azure Automation에서 실행 계정이 아닌 관리 ID를 사용하여 리소스와 상호 작용하는 PowerShell Runbook을 만드는 방법을 안내합니다. PowerShell Runbook은 Windows PowerShell을 기반으로 합니다. Microsoft Entra ID의 관리 ID를 사용하면 Runbook이 Microsoft Entra로 보호되는 다른 리소스에 쉽게 액세스할 수 있습니다.

이 자습서에서는 다음을 하는 방법을 알아볼 수 있습니다.

  • 관리 ID에 사용 권한 할당
  • PowerShell Runbook 생성

Azure 구독이 아직 없는 경우 시작하기 전에 체험 계정을 만듭니다.

사전 요구 사항

관리 ID에 사용 권한 할당

관리 ID에 권한을 할당하여 가상 머신을 중지 및 시작할 수 있도록 합니다.

  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를 사용하여 시스템 할당 관리 ID에 역할을 할당합니다.

    $role1 = "DevTest Labs User"
    
    $SAMI = (Get-AzAutomationAccount -ResourceGroupName $resourceGroup -Name $automationAccount).Identity.PrincipalId
    New-AzRoleAssignment `
        -ObjectId $SAMI `
        -ResourceGroupName $resourceGroup `
        -RoleDefinitionName $role1
    
  4. 사용자 할당 관리 ID에 동일한 역할 할당이 필요합니다.

    $UAMI = (Get-AzUserAssignedIdentity -ResourceGroupName $resourceGroup -Name $userAssignedManagedIdentity).PrincipalId
    New-AzRoleAssignment `
        -ObjectId $UAMI `
        -ResourceGroupName $resourceGroup `
        -RoleDefinitionName $role1
    
  5. 이 자습서에 사용된 대로 cmdlet Get-AzUserAssignedIdentityGet-AzAutomationAccount를 실행하려면 시스템 할당 관리 ID에 대한 추가 권한이 필요합니다.

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

PowerShell Runbook 만들기

관리 ID에서의 실행을 허용하는 Runbook을 만듭니다. Runbook이 중지된 VM을 시작하거나 실행 중인 VM을 중지합니다.

  1. Azure Portal에 로그인하고, Azure Automation 계정으로 이동합니다.

  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은 시스템 할당 관리 ID를 사용하여 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은 명명된 사용자 할당 관리 ID를 사용하여 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

다음 단계

이 자습서에서는 실행 계정이 아닌 관리 ID를 사용하여 Azure Automation에서 PowerShell Runbook을 만들었습니다. PowerShell 워크플로 Runbook에 대한 자세한 내용은 다음을 참조하세요.