Azure Automation에서 리소스와 상호 작용하기 위해 PowerShell Runbook을 만들고, 이를 위해 관리 ID를 사용하는 방법을 이 자습서에서 안내합니다. PowerShell Runbook은 Windows PowerShell을 기반으로 합니다. Microsoft Entra ID 관리 ID를 사용하면 Runbook이 다른 Microsoft Entra 보호된 리소스에 쉽게 액세스할 수 있습니다.
이 자습서에서는 다음을 하는 방법을 알아볼 수 있습니다.
- 관리 ID에 사용 권한 할당
- PowerShell Runbook 생성
Azure 구독이 없는 경우 시작하기 전에 free 계정 만듭니다.
사전 요구 사항
관리 ID에 권한을 할당하기 전에 다음 필수 구성 요소를 충족하는지 확인합니다.
- 사용자 할당 관리 ID가 하나 이상 있는 Azure Automation 계정입니다. 자세한 내용은 Azure Automation 계정에 사용자 할당 관리 ID 사용 참조하세요.
- Az 모듈
Az.Accounts,Az.Automation,Az.ManagedServiceIdentity및Az.Compute를 Automation 계정으로 가져옵니다. 자세한 내용은 Az 모듈 가져오기를 참조하세요. -
Azure Az PowerShell 모듈 컴퓨터에 설치됩니다. 설치하거나 업그레이드하려면 Azure Az PowerShell 모듈을 설치하는 방법 참조하세요.
Az.ManagedServiceIdentity는 미리 보기 모듈이며 Az 모듈의 일부로 설치되지 않습니다. 설치하려면Install-Module -Name Az.ManagedServiceIdentity를 실행합니다. - Azure 가상 머신. 이 머신을 중지하고 시작하므로 프로덕션 VM이 아니어야 합니다.
- 자동화 실행문서에 대해 일반적으로 잘 알고 있습니다.
관리 ID에 사용 권한 할당
관리 ID에 권한을 할당하여 가상 머신을 중지 및 시작할 수 있도록 합니다.
관리 ID에 권한을 할당하려면 다음 단계를 수행합니다.
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>아래 변수에 적절한 값을 입력한 다음 스크립트를 실행합니다.
$resourceGroup = "resourceGroupName" # These values are used in this tutorial $automationAccount = "xAutomationAccount" $userAssignedManagedIdentity = "xUAMI"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사용자 할당 관리 ID에 동일한 역할 할당이 필요합니다.
$UAMI = (Get-AzUserAssignedIdentity -ResourceGroupName $resourceGroup -Name $userAssignedManagedIdentity).PrincipalId New-AzRoleAssignment ` -ObjectId $UAMI ` -ResourceGroupName $resourceGroup ` -RoleDefinitionName $role1이 자습서에 사용된 대로 cmdlet
Get-AzUserAssignedIdentity및Get-AzAutomationAccount를 실행하려면 시스템 할당 관리 ID에 대한 추가 권한이 필요합니다.$role2 = "Reader" New-AzRoleAssignment ` -ObjectId $SAMI ` -ResourceGroupName $resourceGroup ` -RoleDefinitionName $role2
PowerShell Runbook 만들기
관리 대상 ID 중 하나로 실행할 수 있는 Runbook을 만드세요. Runbook은 중지된 VM을 시작하거나 실행 중인 VM을 중지합니다.
PowerShell Runbook을 만들려면 다음 단계를 수행합니다.
Azure 포털 로그인하고 Automation 계정으로 이동합니다.
새 환경에 아직 없는 경우 개요 페이지에서 런타임 환경 환경 사용해보기를 선택합니다.
프로세스 자동화 아래에서 Runbook을 선택합니다.
Runbook 만들기를 선택하고 다음을 수행합니다.
- Runbook의 이름을
miTesting로 설정하세요. - Runbook 형식 드롭다운에서 PowerShell을 선택합니다.
- 런타임 환경 드롭다운에서 기존 런타임 환경을 선택하거나 런타임 PowerShell 및 버전 7.4를 사용하여 새로 만듭니다.
- 해당하는 설명을 입력합니다.
- Runbook의 이름을
만들기를 선택하여 Runbook을 만듭니다.
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편집기에서 줄 8에 필요에 따라
$automationAccount변수의 값을 수정합니다.저장을 선택한 후 테스트 창을 선택합니다.
RESOURCEGROUP및VMNAME매개 변수를 적절한 값으로 채웁니다.SA매개 변수에METHOD를 입력하고xUAMI매개 변수에UAMI를 입력합니다. Runbook은 시스템 할당 관리 ID를 사용하여 VM의 전원 상태를 변경하려고 시도합니다.시작을 선택합니다. 런북이 완료되면, 출력은 다음과 유사하게 표시되어야 합니다.
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@50342METHOD매개 변수의 값을UA로 변경합니다.시작을 선택합니다. Runbook은 명명된 사용자 할당 관리 ID를 사용하여 VM의 전원 상태를 변경하려고 시도합니다. 런북이 완료되면, 출력은 다음과 유사하게 표시되어야 합니다.
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 워크플로 런북에 대한 자세한 내용은 참고하세요.
- PowerShell Runbook을 만드는 동안 관리 ID와 관련된 문제를 해결하려면 Azure Automation 관리 ID 문제 해결을 참조하세요.