البرنامج التعليمي: إنشاء أتمتة سجل تشغيل PowerShell باستخدام الهوية المدارة

يرشدك هذا البرنامج التعليمي خلال إنشاء سجل تشغيل PowerShell في Azure Automation الذي يستخدم الهوية المدارة، بدلاً من حساب Run As للتفاعل مع الموارد. تستند سجلات تشغيل PowerShell إلى Windows PowerShell. تسمح الهوية المدارة من معرف Microsoft Entra لدفتر التشغيل الخاص بك بالوصول بسهولة إلى موارد Microsoft Entra الأخرى المحمية.

في هذا البرنامج التعليمي، تتعلم كيفية:

  • تعيين أذونات للهويات المدارة
  • إنشاء سجل تشغيل PowerShell

في حال لم يكن لديك اشتراك Azure، فأنشئ حساباً مجانيّاً قبل البدء.

المتطلبات الأساسية

تعيين أذونات للهويات المدارة

تعيين أذونات إلى الهويات المدارة للسماح لها بإيقاف تشغيل جهاز ظاهري.

  1. سجّل الدخول إلى Azure بشكل تفاعلي باستخدام Connect-AzAccount cmdlet واتبع الإرشادات.

    # 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. هناك حاجة إلى أذونات إضافية للهوية المُدارة المعينة من قبل النظام لتنفيذ أوامر cmdlets Get-AzUserAssignedIdentity وGet-AzAutomationAccount كما هو مستخدم في هذا البرنامج التعليمي.

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

إنشاء دفتر تسجيل PowerShell

إنشاء دفتر تسجيل يسمح بالتنفيذ بواسطة أي هوية مدارة. سيقوم سجل التشغيل ببدء جهاز ظاهري متوقف أو إيقاف تشغيل جهاز ظاهري.

  1. سجّل الدخول إلى Azure portal، وانتقل إلى حسابك في Automation.

  2. ضمن "Process Automation"، حدد "Runbooks".

  3. حدد "Create a runbook".

    1. قم بتسمية سجل التشغيل miTesting.
    2. من القائمة المنسدلة Runbook type، حدد PowerShell.
    3. من القائمة المنسدلة إصدار وقت التشغيل، حدد إما 7.1 (معاينة) أو 5.1.
    4. أدخل وصفا قابلا للتطبيق.
  4. انقر فوق«إنشاء»لإنشاء دليل التشغيل.

  5. في محرر سجل التشغيل، ألصق الكود التالي:

    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. حدد "Save" ثم "Test pane".

  8. قم بملء المعلمات RESOURCEGROUP وVMNAME بالقيم المناسبة. أدخل SA للمعلمة METHOD وxUAMI للمعلمة UAMI. سيحاول سجل التشغيل تغيير حالة الطاقة للجهاز الظاهري باستخدام الهوية المدارة المعينة من قبل النظام.

  9. حدد بدء. بمجرد اكتمال سجل التشغيل، يجب أن يبدو الإخراج مشابهًا لما يلي:

     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. حدد بدء. سيحاول سجل التشغيل تغيير حالة الطاقة الخاصة بالجهاز الظاهري باستخدام الهوية المدارة المسماة المعينة من قبل المستخدم. بمجرد اكتمال سجل التشغيل، يجب أن يبدو الإخراج مشابهًا لما يلي:

    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
    

حذف الموارد

لإزالة أي موارد لم تعد مطلوبة، قم بتشغيل سجل التشغيل التالي.

#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

الخطوات التالية

في هذا البرنامج التعليمي، قمت بإنشاء دفتر تشغيل PowerShell في Azure Automation الذي استخدم هوية مدارة، بدلا من حساب Run As للتفاعل مع الموارد. لإلقاء نظرة على سجلات تشغيل سير عمل PowerShell، راجع: