Membuat Mesin Virtual DevTest Labs dengan menggunakan Azure PowerShell

Artikel ini menunjukkan cara membuat mesin virtual (VM) Azure DevTest Labs di lab menggunakan Azure PowerShell. Anda dapat menggunakan skrip PowerShell untuk mengotomatiskan pembuatan Mesin Virtual lab.

Prasyarat

Anda memerlukan prasyarat berikut untuk menyelesaikan artikel ini:

Skrip pembuatan Mesin Virtual PowerShell

Cmdlet Invoke-AzResourceAction PowerShell memanggil tindakan createEnvironment dengan ID sumber daya lab dan parameter Mesin Virtual. Parameter berada dalam tabel hash yang berisi semua properti Mesin Virtual. Properti berbeda untuk setiap jenis Mesin Virtual. Untuk mendapatkan properti untuk jenis Mesin Virtual yang Anda inginkan, lihat Mendapatkan properti Mesin Virtual.

Skrip contoh ini membuat Mesin Virtual Pusat Data Windows Server 2019. Sampel juga menyertakan properti untuk menambahkan disk data kedua di bawah dataDiskParameters.

[CmdletBinding()]

Param(
[Parameter(Mandatory = $false)]  $SubscriptionId,
[Parameter(Mandatory = $true)]   $LabResourceGroup,
[Parameter(Mandatory = $true)]   $LabName,
[Parameter(Mandatory = $true)]   $NewVmName,
[Parameter(Mandatory = $true)]   $UserName,
[Parameter(Mandatory = $true)]   $Password
)

pushd $PSScriptRoot

try {
    if ($SubscriptionId -eq $null) {
        $SubscriptionId = (Get-AzContext).Subscription.SubscriptionId
    }

    $API_VERSION = '2016-05-15'
    $lab = Get-AzResource -ResourceId "/subscriptions/$SubscriptionId/resourceGroups/$LabResourceGroup/providers/Microsoft.DevTestLab/labs/$LabName"

    if ($lab -eq $null) {
       throw "Unable to find lab $LabName resource group $LabResourceGroup in subscription $SubscriptionId."
    }

    $virtualNetwork = @(Get-AzResource -ResourceType  'Microsoft.DevTestLab/labs/virtualnetworks' -ResourceName $LabName -ResourceGroupName $lab.ResourceGroupName -ApiVersion $API_VERSION)[0]

    #The preceding command puts the VM in the first allowed subnet in the first virtual network for the lab.
    #If you need to use a specific virtual network, use | to find the network. For example:
    #$virtualNetwork = @(Get-AzResource -ResourceType  'Microsoft.DevTestLab/labs/virtualnetworks' -ResourceName $LabName -ResourceGroupName $lab.ResourceGroupName -ApiVersion $API_VERSION) | Where-Object Name -EQ "SpecificVNetName"

    $labSubnetName = $virtualNetwork.properties.allowedSubnets[0].labSubnetName

    #Prepare all the properties needed for the createEnvironment call.
    # The properties are slightly different depending on the type of VM base.
    # The virtual network setup might also affect the properties.

    $parameters = @{
       "name"      = $NewVmName;
       "location"  = $lab.Location;
       "properties" = @{
          "labVirtualNetworkId"     = $virtualNetwork.ResourceId;
          "labSubnetName"           = $labSubnetName;
          "notes"                   = "Windows Server 2019 Datacenter";
          "osType"                  = "windows"
          "expirationDate"          = "2022-12-01"
          "galleryImageReference"   = @{
             "offer"     = "WindowsServer";
             "publisher" = "MicrosoftWindowsServer";
             "sku"       = "2019-Datacenter";
             "osType"    = "Windows";
             "version"   = "latest"
          };
          "size"                    = "Standard_DS2_v2";
          "userName"                = $UserName;
          "password"                = $Password;
          "disallowPublicIpAddress" = $true;
          "dataDiskParameters" = @(@{
            "attachNewDataDiskOptions" = @{
                "diskName" = "adddatadisk"
                "diskSizeGiB" = "1023"
                "diskType" = "Standard"
                }
          "hostCaching" = "ReadWrite"
          })
       }
    }

    #The following line has the same effect as invoking the
    # https://azure.github.io/projects/apis/#!/Labs/Labs_CreateEnvironment REST API

    Invoke-AzResourceAction -ResourceId $lab.ResourceId -Action 'createEnvironment' -Parameters $parameters -ApiVersion $API_VERSION -Force -Verbose
}
finally {
   popd
}

Simpan skrip sebelumnya dalam file bernama Create-LabVirtualMachine.ps1. Jalankan skrip dengan menggunakan perintah berikut. Masukkan nilai Anda sendiri untuk tempat penampung.

.\Create-LabVirtualMachine.ps1 -ResourceGroupName '<lab resource group name>' -LabName '<lab name>' -userName '<VM administrative username>' -password '<VM admin password>' -VMName '<VM name to create>'

Mendapatkan properti Mesin Virtual

Bagian ini menunjukkan cara mendapatkan properti tertentu untuk jenis Mesin Virtual yang ingin Anda buat. Anda bisa mendapatkan properti dari template Azure Resource Manager (ARM) di portal Microsoft Azure, atau dengan memanggil REST API Azure DevTest Labs.

Menggunakan portal Microsoft Azure untuk mendapatkan properti Mesin Virtual

Membuat Mesin Virtual di portal Microsoft Azure menghasilkan templat Azure Resource Manager (ARM) yang memperlihatkan properti Mesin Virtual. Setelah Anda memilih basis Mesin Virtual, Anda dapat melihat template ARM dan mendapatkan properti tanpa benar-benar membuat Mesin Virtual. Metode ini adalah cara termudah untuk mendapatkan deskripsi Mesin Virtual JSON jika Anda belum memiliki Mesin Virtual lab jenis tersebut.

  1. Di portal Microsoft Azure, pada halaman Gambaran umum lab Anda, pilih Tambahkan di toolbar atas.

  2. Pada halaman Pilih basis, pilih jenis Mesin Virtual yang Anda inginkan. Bergantung pada pengaturan lab, basis Mesin Virtual dapat berupa gambar Marketplace Azure, gambar kustom, rumus, atau lingkungan.

  3. Pada halaman Buat sumber daya lab, secara opsional tambahkan artefak dan konfigurasikan pengaturan lain yang Anda inginkan di tab Pengaturan dasar dan Pengaturan tingkat lanjut.

  4. Pada tab Pengaturan tingkat lanjut, pilih Lihat template ARM di bagian bawah halaman.

  5. Pada halaman Lihat template Azure Resource Manager, tinjau template JSON untuk membuat Mesin Virtual. Bagian sumber daya memiliki properti Mesin Virtual.

    Misalnya, bagian resources berikut memiliki properti untuk Mesin Virtual Pusat Data Windows Server 2022:

      "resources": [
           {
                "apiVersion": "2018-10-15-preview",
                "type": "Microsoft.DevTestLab/labs/virtualmachines",
                "name": "[variables('vmName')]",
                "location": "[resourceGroup().location]",
                "properties": {
                     "labVirtualNetworkId": "[variables('labVirtualNetworkId')]",
                     "notes": "Windows Server 2022 Datacenter: Azure Edition Core",
                     "galleryImageReference": {
                          "offer": "WindowsServer",
                          "publisher": "MicrosoftWindowsServer",
                          "sku": "2022-datacenter-azure-edition-core",
                          "osType": "Windows",
                          "version": "latest"
                     },
                     "size": "[parameters('size')]",
                     "userName": "[parameters('userName')]",
                     "password": "[parameters('password')]",
                     "isAuthenticationWithSshKey": false,
                     "labSubnetName": "[variables('labSubnetName')]",
                     "disallowPublicIpAddress": true,
                     "storageType": "Standard",
                     "allowClaim": false,
                     "networkInterface": {
                          "sharedPublicIpAddressConfiguration": {
                               "inboundNatRules": [
                                    {
                                         "transportProtocol": "tcp",
                                         "backendPort": 3389
                                    }
                               ]
                          }
                     }
                }
           }
      ],
    
  6. Salin dan simpan template untuk digunakan dalam otomatisasi PowerShell di masa mendatang, dan transfer properti ke skrip pembuatan Mesin Virtual PowerShell.

Menggunakan REST API Azure DevTest Labs untuk mendapatkan properti Mesin Virtual

Anda juga dapat memanggil REST API DevTest Labs untuk mendapatkan properti Mesin Virtual lab yang ada. Anda dapat menggunakan properti tersebut untuk membuat lebih banyak Mesin Virtual lab dengan jenis yang sama.

  1. Pada halaman Virtual Machines - daftar, pilih Coba di atas blok kode pertama.
  2. Pada halaman REST API Cobalah:
    • Di bawah labName, masukkan nama lab Anda.
    • Di bawah labResourceGroup, masukkan nama grup sumber daya lab.
    • Di bawah subscriptionId, pilih langganan Azure lab.
  3. Pilih Jalankan.
  4. Di bagian Respons di bawah Isi, lihat properti untuk semua Mesin Virtual yang ada di lab.

Mengatur kedaluwarsa Mesin Virtual

Dalam skenario pelatihan, demo, dan percobaan, Anda dapat menghindari biaya yang tidak perlu dengan menghapus Mesin Virtual secara otomatis pada tanggal tertentu. Anda dapat mengatur properti expirationDate Mesin Virtual saat membuat Mesin Virtual. Skrip pembuatan Mesin Virtual PowerShell sebelumnya dalam artikel ini menetapkan kedaluwarsa di bawah properties:

  "expirationDate": "2022-12-01"

Anda juga dapat mengatur kedaluwarsa pada Mesin Virtual yang ada dengan menggunakan PowerShell. Skrip PowerShell berikut menetapkan kedaluwarsa untuk Mesin Virtual lab yang ada jika belum memiliki kedaluwarsa:

# Enter your own values:
$subscriptionId = '<Lab subscription Id>'
$labResourceGroup = '<Lab resource group>'
$labName = '<Lab name>'
$VmName = '<VM name>'
$expirationDate = '<Expiration date, such as 2022-12-16>'

# Sign in to your Azure account

Select-AzSubscription -SubscriptionId $subscriptionId
$VmResourceId = "subscriptions/$subscriptionId/resourcegroups/$labResourceGroup/providers/microsoft.devtestlab/labs/$labName/virtualmachines/$VmName"

$vm = Get-AzResource -ResourceId $VmResourceId -ExpandProperties

# Get the Vm properties
$VmProperties = $vm.Properties

# Set the expirationDate property
If ($VmProperties.expirationDate -eq $null) {
    $VmProperties | Add-Member -MemberType NoteProperty -Name expirationDate -Value $expirationDate -Force
} Else {
    $VmProperties.expirationDate = $expirationDate
}

Set-AzResource -ResourceId $VmResourceId -Properties $VmProperties -Force

Langkah berikutnya

Referensi PowerShell Az.DevTestLabs