教程:通过 Azure PowerShell 创建和使用虚拟机规模集的自定义映像Tutorial: Create and use a custom image for virtual machine scale sets with Azure PowerShell

创建规模集时,需指定部署 VM 实例时要使用的映像。When you create a scale set, you specify an image to be used when the VM instances are deployed. 若要在部署 VM 实例之后减少任务数目,可以使用自定义 VM 映像。To reduce the number of tasks after VM instances are deployed, you can use a custom VM image. 在此自定义 VM 映像中可以完成全部所需的应用程序安装或配置步骤。This custom VM image includes any required application installs or configurations. 在规模集中创建的任何 VM 实例使用自定义 VM 映像,并随时可为应用程序流量提供服务。Any VM instances created in the scale set use the custom VM image and are ready to serve your application traffic. 本教程介绍如何执行下列操作:In this tutorial you learn how to:

  • 创建共享映像库Create a Shared Image Gallery
  • 创建映像定义Create an image definition
  • 创建映像版本Create an image version
  • 从映像创建规模集Create a scale-set from an image
  • 共享映像库Share an image gallery

如果没有 Azure 订阅,可在开始前创建一个试用帐户If you don't have an Azure subscription, create a Trial before you begin.

准备阶段Before you begin

下列步骤详细说明如何将现有 VM 转换为可重用自定义映像,以便将其用于创建规模集。The steps below detail how to take an existing VM and turn it into a re-usable custom image that you can use to create a scale set.

若要完成本教程中的示例,必须现有一个虚拟机。To complete the example in this tutorial, you must have an existing virtual machine. 如果需要,可以参阅 PowerShell 快速入门来创建本教程所用的 VM。If needed, you can see the PowerShell quickstart to create a VM to use for this tutorial. 在学习本教程期间,请根据需要替换资源名称。When working through the tutorial, replace the resource names where needed.

获取 VMGet the VM

可以使用 Get-AzVM 查看资源组中可用的 VM 列表。You can see a list of VMs that are available in a resource group using Get-AzVM. 了解 VM 名称和资源组后,可以再次使用 Get-AzVM 来获取 VM 对象并将其存储在变量中,供稍后使用。Once you know the VM name and what resource group, you can use Get-AzVM again to get the VM object and store it in a variable to use later. 此示例从“myResourceGroup”资源组获取名为 sourceVM 的 VM,并将其分配给变量 $vm 。This example gets an VM named sourceVM from the "myResourceGroup" resource group and assigns it to the variable $vm.

$sourceVM = Get-AzVM `
   -Name sourceVM `
   -ResourceGroupName myResourceGroup

创建资源组Create a resource group

使用 New-AzResourceGroup 命令创建资源组。Create a resource group with the New-AzResourceGroup command.

Azure 资源组是在其中部署和管理 Azure 资源的逻辑容器。An Azure resource group is a logical container into which Azure resources are deployed and managed. 以下示例在“ChinaNorth”区域中创建名为“myGalleryRG”的资源组 :In the following example, a resource group named myGalleryRG is created in the ChinaNorth region:

$resourceGroup = New-AzResourceGroup `
   -Name 'myGalleryRG' `
   -Location 'ChinaNorth'

映像库是用于启用映像共享的主要资源。An image gallery is the primary resource used for enabling image sharing. 允许用于库名称的字符为大写或小写字母、数字、点和句点。Allowed characters for gallery name are uppercase or lowercase letters, digits, dots, and periods. 库名称不能包含短划线。The gallery name cannot contain dashes. 库名称在你的订阅中必须唯一。Gallery names must be unique within your subscription.

使用 New-AzGallery 创建映像库。Create an image gallery using New-AzGallery. 以下示例在“myGalleryRG”资源组中创建名为“myGallery”的库 。The following example creates a gallery named myGallery in the myGalleryRG resource group.

$gallery = New-AzGallery `
   -GalleryName 'myGallery' `
   -ResourceGroupName $resourceGroup.ResourceGroupName `
   -Location $resourceGroup.Location `
   -Description 'Shared Image Gallery for my organization'  

创建映像定义Create an image definition

映像定义为映像创建逻辑分组。Image definitions create a logical grouping for images. 映像定义用于管理在其中创建的映像版本的相关信息。They are used to manage information about the image versions that are created within them. 映像定义名称可以由大写或小写字母、数字、点、短划线和句点构成。Image definition names can be made up of uppercase or lowercase letters, digits, dots, dashes and periods. 有关可为映像定义指定的值的详细信息,请参阅映像定义For more information about the values you can specify for an image definition, see Image definitions.

使用 New-AzGalleryImageDefinition 创建映像定义。Create the image definition using New-AzGalleryImageDefinition. 在此示例中,库映像名为 myGalleryImage,它是为专用化映像创建的。In this example, the gallery image is named myGalleryImage and is created for a specialized image.

$galleryImage = New-AzGalleryImageDefinition `
   -GalleryName $gallery.Name `
   -ResourceGroupName $resourceGroup.ResourceGroupName `
   -Location $gallery.Location `
   -Name 'myImageDefinition' `
   -OsState specialized `
   -OsType Windows `
   -Publisher 'myPublisher' `
   -Offer 'myOffer' `
   -Sku 'mySKU'

创建映像版本Create an image version

使用 New-AzGalleryImageVersion 从 VM 创建映像版本。Create an image version from a VM using New-AzGalleryImageVersion.

允许用于映像版本的字符为数字和句点。Allowed characters for image version are numbers and periods. 数字必须在 32 位整数范围内。Numbers must be within the range of a 32-bit integer. 格式:MajorVersion.MinorVersion.PatchFormat: MajorVersion.MinorVersion.Patch.

在此示例中,映像版本为 1.0.0,该版本被复制到中国北部和中国北部数据中心 。In this example, the image version is 1.0.0 and it's replicated to both China North and China North datacenters. 选择复制的目标区域时,需要将源区域包含为复制目标。When choosing target regions for replication, you need to include the source region as a target for replication.

若要从 VM 创建映像版本,请对 -Source 使用 $vm.Id.ToString()To create an image version from the VM, use $vm.Id.ToString() for the -Source.

$region1 = @{Name='China North';ReplicaCount=1}
$region2 = @{Name='China North';ReplicaCount=2}
$targetRegions = @($region1,$region2)

New-AzGalleryImageVersion `
   -GalleryImageDefinitionName $galleryImage.Name`
   -GalleryImageVersionName '1.0.0' `
   -GalleryName $gallery.Name `
   -ResourceGroupName $resourceGroup.ResourceGroupName `
   -Location $resourceGroup.Location `
   -TargetRegion $targetRegions  `
   -Source $sourceVM.Id.ToString() `
   -PublishingProfileEndOfLifeDate '2020-12-01'

可能需要一段时间才能将映像复制到所有目标区域。It can take a while to replicate the image to all of the target regions.

从映像创建规模集Create a scale set from the image

现在,请使用 New-AzVmss 来创建规模集,前者使用 -ImageName 参数来定义在上一步创建的自定义 VM 映像。Now create a scale set with New-AzVmss that uses the -ImageName parameter to define the custom VM image created in the previous step. 若要将流量分配到单独的 VM 实例,则还要创建负载均衡器。To distribute traffic to the individual VM instances, a load balancer is also created. 负载均衡器包含的规则可在 TCP 端口 80 上分配流量,并允许 TCP 端口 3389 上的远程桌面流量,以及 TCP 端口 5985 上的 PowerShell 远程流量。The load balancer includes rules to distribute traffic on TCP port 80, as well as allow remote desktop traffic on TCP port 3389 and PowerShell remoting on TCP port 5985. 出现提示时,请针对规模集中的 VM 实例提供自己的所需管理凭据:When prompted, provide your own desired administrative credentials for the VM instances in the scale set:

# Define variables for the scale set
$resourceGroupName = "myVMSSRG3"
$scaleSetName = "myScaleSet3"
$location = "China North"

# Create a resource group
New-AzResourceGroup -ResourceGroupName $resourceGroupName -Location $location

# Create a networking pieces
$subnet = New-AzVirtualNetworkSubnetConfig `
  -Name "mySubnet" `
  -AddressPrefix 10.0.0.0/24
$vnet = New-AzVirtualNetwork `
  -ResourceGroupName $resourceGroupName `
  -Name "myVnet" `
  -Location $location `
  -AddressPrefix 10.0.0.0/16 `
  -Subnet $subnet
$publicIP = New-AzPublicIpAddress `
  -ResourceGroupName $resourceGroupName `
  -Location $location `
  -AllocationMethod Static `
  -Name "myPublicIP"
$frontendIP = New-AzLoadBalancerFrontendIpConfig `
  -Name "myFrontEndPool" `
  -PublicIpAddress $publicIP
$backendPool = New-AzLoadBalancerBackendAddressPoolConfig -Name "myBackEndPool"
$inboundNATPool = New-AzLoadBalancerInboundNatPoolConfig `
  -Name "myRDPRule" `
  -FrontendIpConfigurationId $frontendIP.Id `
  -Protocol TCP `
  -FrontendPortRangeStart 50001 `
  -FrontendPortRangeEnd 50010 `
  -BackendPort 3389
# Create the load balancer and health probe
$lb = New-AzLoadBalancer `
  -ResourceGroupName $resourceGroupName `
  -Name "myLoadBalancer" `
  -Location $location `
  -FrontendIpConfiguration $frontendIP `
  -BackendAddressPool $backendPool `
  -InboundNatPool $inboundNATPool
Add-AzLoadBalancerProbeConfig -Name "myHealthProbe" `
  -LoadBalancer $lb `
  -Protocol TCP `
  -Port 80 `
  -IntervalInSeconds 15 `
  -ProbeCount 2
Add-AzLoadBalancerRuleConfig `
  -Name "myLoadBalancerRule" `
  -LoadBalancer $lb `
  -FrontendIpConfiguration $lb.FrontendIpConfigurations[0] `
  -BackendAddressPool $lb.BackendAddressPools[0] `
  -Protocol TCP `
  -FrontendPort 80 `
  -BackendPort 80 `
  -Probe (Get-AzLoadBalancerProbeConfig -Name "myHealthProbe" -LoadBalancer $lb)
Set-AzLoadBalancer -LoadBalancer $lb

# Create IP address configurations
$ipConfig = New-AzVmssIpConfig `
  -Name "myIPConfig" `
  -LoadBalancerBackendAddressPoolsId $lb.BackendAddressPools[0].Id `
  -LoadBalancerInboundNatPoolsId $inboundNATPool.Id `
  -SubnetId $vnet.Subnets[0].Id

# Create a configuration 
$vmssConfig = New-AzVmssConfig `
    -Location $location `
    -SkuCapacity 2 `
    -SkuName "Standard_DS2" `
    -UpgradePolicyMode "Automatic"

# Reference the image version
Set-AzVmssStorageProfile $vmssConfig `
  -OsDiskCreateOption "FromImage" `
  -ImageReferenceId $galleryImage.Id

# Complete the configuration
 
Add-AzVmssNetworkInterfaceConfiguration `
  -VirtualMachineScaleSet $vmssConfig `
  -Name "network-config" `
  -Primary $true `
  -IPConfiguration $ipConfig 

# Create the scale set 
New-AzVmss `
  -ResourceGroupName $resourceGroupName `
  -Name $scaleSetName `
  -VirtualMachineScaleSet $vmssConfig

创建和配置所有的规模集资源和 VM 需要几分钟时间。It takes a few minutes to create and configure all the scale set resources and VMs.

建议在映像库级别共享访问权限。We recommend that you share access at the image gallery level. 使用电子邮件地址和 Get-AzADUser cmdlet 获取用户的对象 ID,然后使用 New-AzRoleAssignment 为用户授予对库的访问权限。Use an email address and the Get-AzADUser cmdlet to get the object ID for the user, then use New-AzRoleAssignment to give them access to the gallery. 请将此示例中的示例电子邮件地址 alinne_montes@contoso.com 替换为你自己的信息。Replace the example email, alinne_montes@contoso.com in this example, with your own information.

# Get the object ID for the user
$user = Get-AzADUser -StartsWith alinne_montes@contoso.com
# Grant access to the user for our gallery
New-AzRoleAssignment `
   -ObjectId $user.Id `
   -RoleDefinitionName Reader `
   -ResourceName $gallery.Name `
   -ResourceType Microsoft.Compute/galleries `
   -ResourceGroupName $resourceGroup.ResourceGroupName

清理资源Clean up resources

不再需要时,可以使用 Remove-AzResourceGroup cmdlet 删除资源组和所有相关资源:When no longer needed, you can use the Remove-AzResourceGroup cmdlet to remove the resource group, and all related resources:

# Delete the gallery 
Remove-AzResourceGroup -Name myGalleryRG

# Delete the scale set resource group
Remove-AzResourceGroup -Name myResoureceGroup

Azure 映像生成器Azure Image Builder

Azure 还提供一个基于 Packer 的服务:Azure VM 映像生成器。Azure also offers a service, built on Packer, Azure VM Image Builder. 只需在模板中描述你的自定义设置,然后该模板即会处理映像的创建。Simply describe your customizations in a template, and it will handle the image creation.

后续步骤Next steps

本教程介绍了如何通过 Azure PowerShell 创建和使用规模集的自定义 VM 映像:In this tutorial, you learned how to create and use a custom VM image for your scale sets with Azure PowerShell:

  • 创建共享映像库Create a Shared Image Gallery
  • 创建映像定义Create an image definition
  • 创建映像版本Create an image version
  • 从映像创建规模集Create a scale-set from an image
  • 共享映像库Share an image gallery

请继续学习下一教程,了解如何将应用程序部署到规模集。Advance to the next tutorial to learn how to deploy applications to your scale set.