你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。

使用 Azure PowerShell 创建开发测试实验室 VM

本文介绍如何使用 Azure PowerShell 在实验室中创建 Azure 开发测试实验室虚拟机 (VM)。 可以使用 PowerShell 脚本自动创建实验室 VM。

先决条件

要完成本文中的步骤,需要符合以下先决条件:

PowerShell VM 创建脚本

PowerShell Invoke-AzResourceAction cmdlet 通过实验室的资源 ID 和 VM 参数来调用 createEnvironment 操作。 参数位于一个包含所有 VM 属性的哈希表中。 每种 VM 类型的属性各不相同。 若要获取所需 VM 类型的属性,请参阅获取 VM 属性。

此示例脚本创建了一个 Windows Server 2019 Datacenter VM。 该示例还包括在 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
}

将前面的脚本保存在一个名为 Create-LabVirtualMachine.ps1 的文件中。 使用以下命令运行该脚本。 在占位符处输入你自己的值。

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

获取 VM 属性

本部分介绍如何获取你想要创建的 VM 类型的特定属性。 可以在 Azure 门户中从 Azure 资源管理器 (ARM) 模板获取属性,也可以通过调用开发测试实验室 Azure REST API 获取属性。

使用 Azure 门户获取 VM 属性

在 Azure 门户中创建 VM 会生成一个 Azure 资源管理器 (ARM) 模板,其中显示 VM 的属性。 选择 VM 基础映像后,可以查看 ARM 模板并获取属性,而无需实际创建 VM。 如果你还没有相应类型的实验室 VM,那么这种方法是获取 JSON VM 描述的最简单方法。

  1. 在 Azure 门户中,在实验室的“概述”页上,选择顶部工具栏上的“添加”。

  2. 在“选择基础映像”页上,选择所需的 VM 类型。 根据实验室设置,VM 基础映像可以是 Azure 市场映像、自定义映像、公式或环境。

  3. 在“创建实验室资源”页上,可以选择添加项目,并在“基本设置”和“高级设置”选项卡上配置所需的任何其他设置。

  4. 在“高级设置”选项卡上,选择页面底部的“查看 ARM 模板”。

  5. 在“查看 Azure 资源管理器模板”页上,查看用于创建 VM 的 JSON 模板。 “资源”部分包含 VM 属性。

    例如,以下 resources 部分包含 Windows Server 2022 Datacenter VM 的属性:

      "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. 复制并保存模板,以便在将来的 PowerShell 自动化中使用,并将属性传输到 PowerShell VM 创建脚本。

使用开发测试实验室 Azure REST API 获取 VM 属性

你还可以调用开发测试实验室 REST API 来获取现有实验室 VM 的属性。 可以使用这些属性创建更多相同类型的实验室 VM。

  1. 在“虚拟机 - 列表”页上,选择第一个代码块上方的“试用”。
  2. 在“REST API 试用”页上:
    • 在“labName”下,输入实验室名称。
    • 在“labResourceGroup”下,输入实验室资源组名称。
    • 在“subscriptionId”下,选择实验室的 Azure 订阅。
  3. 选择“运行”。
  4. 在“正文”下的“响应”部分中,查看实验室中所有现有 VM 的属性。

设置 VM 过期日期

在培训、演示和试用场景中,可以通过在特定日期自动删除 VM 来避免不必要的成本。 在创建 VM 时,可以设置 VM 的 expirationDate 属性。 本文前面的 PowerShell VM 创建脚本将在 properties 下设置到期日期:

  "expirationDate": "2022-12-01"

此外,还可以使用 PowerShell 对现有 VM 设置到期日期。 如果现有实验室 VM 还没有到期日期,以下 PowerShell 脚本可以为其设置一个到期日期:

# 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

后续步骤

Az.DevTestLabs PowerShell 参考