Tutorial: Membuat runbook PowerShell di Automation menggunakan identitas terkelola

Tutorial ini akan memandu Anda dalam membuat runbook PowerShell di Azure Automation yang menggunakan identitas terkelola, bukan akun Jalankan Sebagai untuk berinteraksi dengan sumber daya. Runbook PowerShell berbasis Windows PowerShell. Identitas terkelola dari MICROSOFT Entra ID memungkinkan runbook Anda untuk dengan mudah mengakses sumber daya yang dilindungi Microsoft Entra lainnya.

Dalam tutorial ini, Anda akan mempelajari cara:

  • Tetapkan izin untuk identitas terkelola
  • Buat runbook PowerShell

Jika Anda tidak memiliki langganan Azure, buat akun gratis sebelum Anda memulai.

Prasyarat

Tetapkan izin untuk identitas terkelola

Tetapkan izin ke identitas terkelola untuk memungkinkan mereka menghentikan dan memulai mesin virtual.

  1. Masuk ke Azure secara interaktif menggunakan cmdlet Connect-AzAccount dan ikuti instruksinya.

    # 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. Berikan nilai yang sesuai untuk variabel di bawah ini dan kemudian jalankan skrip.

    $resourceGroup = "resourceGroupName"
    
    # These values are used in this tutorial
    $automationAccount = "xAutomationAccount"
    $userAssignedManagedIdentity = "xUAMI"
    
  3. Gunakan cmdlet PowerShell New-AzRoleAssignment untuk menetapkan peran ke identitas terkelola yang ditetapkan sistem.

    $role1 = "DevTest Labs User"
    
    $SAMI = (Get-AzAutomationAccount -ResourceGroupName $resourceGroup -Name $automationAccount).Identity.PrincipalId
    New-AzRoleAssignment `
        -ObjectId $SAMI `
        -ResourceGroupName $resourceGroup `
        -RoleDefinitionName $role1
    
  4. Tugas peran yang sama diperlukan untuk identitas terkelola yang ditetapkan pengguna

    $UAMI = (Get-AzUserAssignedIdentity -ResourceGroupName $resourceGroup -Name $userAssignedManagedIdentity).PrincipalId
    New-AzRoleAssignment `
        -ObjectId $UAMI `
        -ResourceGroupName $resourceGroup `
        -RoleDefinitionName $role1
    
  5. Izin tambahan untuk identitas terkelola yang ditetapkan sistem diperlukan untuk menjalankan cmdlet Get-AzUserAssignedIdentity dan Get-AzAutomationAccount sebagaimana yang digunakan dalam tutorial ini.

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

Membuat runbook PowerShell

Membuat runbook yang akan memungkinkan eksekusi dengan identitas terkelola. Runbook akan memulai VM yang dihentikan, atau menghentikan VM yang sedang berjalan.

  1. Masuk ke portal Microsoft Azure, dan navigasikan ke akun Azure Automation Anda.

  2. Di Proses Automasi, pilih Runbook.

  3. Pilih Buat runbook.

    1. Beri nama runbook miTesting.
    2. Dari menu drop-down Jenis runbook, pilih PowerShell.
    3. Dari menu drop-down Versi runtime, pilih 7.1 (pratinjau) atau 5.1.
    4. Masukkan Deskripsi yang berlaku.
  4. Klik Buat untuk membuat runbook.

  5. Di editor runbook, tempel kode berikut:

    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. Di editor, pada baris 8, revisi nilai untuk variabel $automationAccount ​​sesuai kebutuhan.

  7. Pilih Simpan lalu panel Uji.

  8. Isi parameter RESOURCEGROUP dan VMNAME dengan nilai yang sesuai. Masukkan SA untuk parameter METHOD dan xUAMI untuk parameter UAMI. Runbook akan mencoba mengubah status kekuatan VM Anda menggunakan identitas terkelola yang ditetapkan sistem.

  9. Pilih Mulai. Setelah runbook selesai, output harus terlihat mirip seperti berikut:

     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. Ubah nilai parameter METHOD menjadi UA.

  11. Pilih Mulai. Runbook akan mencoba mengubah status kekuatan VM Anda menggunakan identitas terkelola yang ditetapkan pengguna. Setelah runbook selesai, output harus terlihat mirip seperti berikut:

    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
    

Membersihkan Sumber Daya

Untuk menghapus sumber daya apa pun yang tidak diperlukan lagi, jalankan runbook berikut.

#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

Langkah berikutnya

Dalam tutorial ini, Anda membuat runbook PowerShell di Azure Automation yang menggunakan identitas terkelola, bukan akun Jalankan Sebagai untuk berinteraksi dengan sumber daya. Untuk melihat runbook Alur Kerja PowerShell, lihat: