教程:使用 Azure PowerShell 自动缩放虚拟机规模集Tutorial: Automatically scale a virtual machine scale set with Azure PowerShell


使用 PowerShell 的 Azure 功能必须已安装 AzureRM 模块。Using this Azure feature from PowerShell requires the AzureRM module installed. 该模块是旧模块,仅适用于 Windows PowerShell 5.1,它不再接收新功能。This is an older module only available for Windows PowerShell 5.1 that no longer receives new features. 针对相同版本的 PowerShell 进行安装时,AzAzureRM 模块不兼容。The Az and AzureRM modules are not compatible when installed for the same versions of PowerShell. 如果需要两个版本,请执行以下操作:If you need both versions:

  1. 在 PowerShell 5.1 会话中卸载 Az 模块Uninstall the Az module from a PowerShell 5.1 session.
  2. 在 PowerShell 5.1 会话中安装 AzureRM 模块Install the AzureRM module from a PowerShell 5.1 session.
  3. 下载并安装 PowerShell Core 6.x 或更高版本Download and install PowerShell Core 6.x or later.
  4. 在 PowerShell Core 会话中安装 Az 模块Install the Az module in a PowerShell Core session.

创建规模集时,可定义想运行的 VM 实例数。When you create a scale set, you define the number of VM instances that you wish to run. 若应用程序需要更改,可自动增加或减少 VM 实例数。As your application demand changes, you can automatically increase or decrease the number of VM instances. 通过自动缩放功能,可随客户需求的改变而进行调整,或在应用的整个生命周期内响应应用程序性能更改。The ability to autoscale lets you keep up with customer demand or respond to application performance changes throughout the lifecycle of your app. 本教程介绍如何执行下列操作:In this tutorial you learn how to:

  • 对规模集使用自动缩放Use autoscale with a scale set
  • 创建和使用自动缩放规则Create and use autoscale rules
  • 对 VM 实例进行压力测试并触发自动缩放规则Stress-test VM instances and trigger autoscale rules
  • 在需求下降时自动横向缩减Autoscale back in as demand is reduced

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

存在影响 Azure PowerShell 模块版本 6.8.1 或更高版本的已知问题。There's a known issue that affects Azure PowerShell module version 6.8.1 or later. 本教程只能使用 Azure PowerShell 模块版本 6.0.0 到 6.8.0 运行。This tutorial can only run using Azure PowerShell module version 6.0.0 to 6.8.0. 运行 Get-Module -ListAvailable AzureRM 即可查找版本。Run Get-Module -ListAvailable AzureRM to find the version. 如果在本地运行 PowerShell,则还需运行 Connect-AzureRmAccount 来创建与 Azure 的连接。If you are running PowerShell locally, you also need to run Connect-AzureRmAccount to create a connection with Azure.

创建规模集Create a scale set

若要更轻松地创建自动缩放规则,请为规模集定义几个变量。To make it easier to create the autoscale rules, define some variables for your scale set. 以下示例为 myResourceGroup 资源组和“中国北部”区域内名为 myScaleSet 的规模集定义变量 。The following example defines variables for the scale set named myScaleSet in the resource group named myResourceGroup and in the China North region. 使用 Get-AzureRmSubscription 获取订阅 ID。Your subscription ID is obtained with Get-AzureRmSubscription. 如果帐户关联了多个订阅,则仅返回第一个订阅。If you have multiple subscriptions associated with your account, only the first subscription is returned. 按照如下所示,调整名称和订阅 ID:Adjust the names and subscription ID as follows:

$mySubscriptionId = (Get-AzureRmSubscription)[0].Id
$myResourceGroup = "myResourceGroup"
$myScaleSet = "myScaleSet"
$myLocation = "China North"

现在,使用 New-AzureRmVmss 创建虚拟机规模集。Now create a virtual machine scale set with New-AzureRmVmss. 若要将流量分配到单独的 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:

New-AzureRmVmss `
  -ResourceGroupName $myResourceGroup `
  -VMScaleSetName $myScaleSet `
  -Location $myLocation `
  -VirtualNetworkName "myVnet" `
  -SubnetName "mySubnet" `
  -PublicIpAddressName "myPublicIPAddress" `
  -LoadBalancerName "myLoadBalancer"

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

创建规则,以便自动横向扩展Create a rule to autoscale out

如果应用程序需求提高,规模集中 VM 实例上的负载将会增大。If your application demand increases, the load on the VM instances in your scale set increases. 如果这种负载增大持续稳定,而不只是短暂的需求,那么可以配置自动缩放规则来增加规模集中的 VM 实例数。If this increased load is consistent, rather than just a brief demand, you can configure autoscale rules to increase the number of VM instances in the scale set. 创建这些 VM 实例并部署应用程序后,规模集会开始通过负载均衡器将流量分配到这些实例和应用程序。When these VM instances are created and your applications are deployed, the scale set starts to distribute traffic to them through the load balancer. 可以控制要监视的指标(例如 CPU 或磁盘)、应用程序负载必须处于给定阈值内的时间,以及要添加到规模集的 VM 实例数。You control what metrics to monitor, such as CPU or disk, how long the application load must meet a given threshold, and how many VM instances to add to the scale set.

平均 CPU 负载大于 70% 持续了 5 分多钟时,请使用 New-AzureRmAutoscaleRule 创建规则增加规模集中的 VM 实例数。Let's create a rule with New-AzureRmAutoscaleRule that increases the number of VM instances in a scale set when the average CPU load is greater than 70% over a 5-minute period. 触发规则时,VM 实例数增加 3。When the rule triggers, the number of VM instances is increased by three.

此规则使用以下参数:The following parameters are used for this rule:

参数Parameter 说明Explanation Value
-MetricName-MetricName 监视和应用规模集操作的性能指标。The performance metric to monitor and apply scale set actions on. CPU 百分比Percentage CPU
-TimeGrain-TimeGrain 为进行而收集指标分析的频率。How often the metrics are collected for analysis. 1 分钟1 minute
-MetricStatistic-MetricStatistic 定义如何聚合已收集的指标以便分析。Defines how the collected metrics should be aggregated for analysis. 平均值Average
-TimeWindow-TimeWindow 比较指标与阈值之前监视的时长。The amount of time monitored before the metric and threshold values are compared. 5 分钟5 minutes
-Operator-Operator 用于比较指标数据和阈值的运算符。Operator used to compare the metric data against the threshold. 大于Greater Than
-Threshold-Threshold 使自动缩放规则触发操作的值。The value that causes the autoscale rule to trigger an action. 70%70%
-ScaleActionDirection-ScaleActionDirection 定义应用规则时,规模集应扩展还是缩减。Defines if the scale set should scale up or down when the rule applies. 增加Increase
-ScaleActionScaleType-ScaleActionScaleType 表明 VM 实例数应该根据特定值进行更改。Indicates that the number of VM instances should be changed by a specific value. 更改计数Change Count
-ScaleActionValue-ScaleActionValue 规则触发时,应更改 VM 实例的百分比。The percentage of VM instances should be changed when the rule triggers. 33
-ScaleActionCooldown-ScaleActionCooldown 为使自动缩放操作有时间生效,再次应用规则前需要等待的时间。The amount of time to wait before the rule is applied again so that the autoscale actions have time to take effect. 5 分钟5 minutes

以下示例将创建名为 myRuleScaleOut 的对象,用于保存此扩展规则。The following example creates an object named myRuleScaleOut that holds this scale up rule. -MetricResourceId 使用以前为订阅 ID、资源组名称和规模集名称定义的变量 :The -MetricResourceId uses the variables previously defined for the subscription ID, resource group name, and scale set name:

$myRuleScaleOut = New-AzureRmAutoscaleRule `
  -MetricName "Percentage CPU" `
  -MetricResourceId /subscriptions/$mySubscriptionId/resourceGroups/$myResourceGroup/providers/Microsoft.Compute/virtualMachineScaleSets/$myScaleSet `
  -TimeGrain 00:01:00 `
  -MetricStatistic "Average" `
  -TimeWindow 00:05:00 `
  -Operator "GreaterThan" `
  -Threshold 70 `
  -ScaleActionDirection "Increase" `
  -ScaleActionScaleType "ChangeCount" `
  -ScaleActionValue 3 `
  -ScaleActionCooldown 00:05:00

创建规则,以便自动横向缩减Create a rule to autoscale in

在夜间或周末,应用程序需求可能会降低。On an evening or weekend, your application demand may decrease. 如果这种负载降低在一段时间内持续稳定,可以配置自动缩放规则来减少规模集中的 VM 实例数。If this decreased load is consistent over a period of time, you can configure autoscale rules to decrease the number of VM instances in the scale set. 这种横向缩减操作可以减少运行规模集所需的成本,因为只运行满足当前需求所需的实例数。This scale-in action reduces the cost to run your scale set as you only run the number of instances required to meet the current demand.

平均 CPU 负载小于 30% 持续了 5 分钟时,请使用 New-AzureRmAutoscaleRule 创建另一规则来减少规模集中的 VM 实例数。Create another rule with New-AzureRmAutoscaleRule that decreases the number of VM instances in a scale set when the average CPU load then drops below 30% over a 5-minute period. 触发规则后,VM 实例数减少 1。When the rule triggers, the number of VM instances is decreased by one. 以下示例将创建名为“myRuleScaleDown”的对象,用于保存此缩减规则。The following example creates an object named myRuleScaleDown that holds this scale down rule. -MetricResourceId 使用以前为订阅 ID、资源组名称和规模集名称定义的变量 :The -MetricResourceId uses the variables previously defined for the subscription ID, resource group name, and scale set name:

$myRuleScaleIn = New-AzureRmAutoscaleRule `
  -MetricName "Percentage CPU" `
  -MetricResourceId /subscriptions/$mySubscriptionId/resourceGroups/$myResourceGroup/providers/Microsoft.Compute/virtualMachineScaleSets/$myScaleSet `
  -Operator "LessThan" `
  -MetricStatistic "Average" `
  -Threshold 30 `
  -TimeGrain 00:01:00 `
  -TimeWindow 00:05:00 `
  -ScaleActionCooldown 00:05:00 `
  -ScaleActionDirection "Decrease" `
  -ScaleActionScaleType "ChangeCount" `
  -ScaleActionValue 1

定义自动缩放配置文件Define an autoscale profile

若要将自动缩放规则与规模集相关联,请创建一个配置文件。To associate your autoscale rules with a scale set, create a profile. 自动缩放配置文件定义了默认值、最小规模集容量和最大规模集容量,并与自动缩放规则关联。The autoscale profile defines the default, minimum, and maximum scale set capacity, and associates your autoscale rules. 使用 New-AzureRmAutoscaleProfile 创建自动缩放配置文件。Create an autoscale profile with New-AzureRmAutoscaleProfile. 以下示例设置了默认值,以及最小容量 2 个 VM 实例、最大容量 10 个 VM 。The following example sets the default, and minimum, capacity of 2 VM instances, and a maximum of 10. 然后附加前几步中创建的横向扩展和横向缩减规则:The scale out and scale in rules created in the preceding steps are then attached:

$myScaleProfile = New-AzureRmAutoscaleProfile `
  -DefaultCapacity 2  `
  -MaximumCapacity 10 `
  -MinimumCapacity 2 `
  -Rule $myRuleScaleOut,$myRuleScaleIn `
  -Name "autoprofile"

将自动缩放配置文件应用于规模集Apply autoscale profile to a scale set

最后一步是将自动缩放配置文件应用于规模集。The final step is to apply the autoscale profile to your scale set. 随后,规模集便能根据应用程序需求自动进行横向缩减或扩展。Your scale set is then able to automatically scale in or out based on the application demand. 使用 Add-AzureRmAutoscaleSetting 应用自动缩放配置文件,如下所示:Apply the autoscale profile with Add-AzureRmAutoscaleSetting as follows:

Add-AzureRmAutoscaleSetting `
  -Location $myLocation `
  -Name "autosetting" `
  -ResourceGroup $myResourceGroup `
  -TargetResourceId /subscriptions/$mySubscriptionId/resourceGroups/$myResourceGroup/providers/Microsoft.Compute/virtualMachineScaleSets/$myScaleSet `
  -AutoscaleProfile $myScaleProfile

在规模集上生成 CPU 负载Generate CPU load on scale set

若要测试自动缩放规则,请在规模集的 VM 实例上生成一些 CPU 负载。To test the autoscale rules, generate some CPU load on the VM instances in the scale set. 这种模拟的 CPU 负载会导致自动缩放规则以横向扩展的方式增加 VM 实例数。This simulated CPU load causes the autoscale rules to scale out and increase the number of VM instances. 随着模拟的 CPU 负载下降,自动缩放规则会进行横向缩减,减少 VM 实例数。As the simulated CPU load is then decreased, the autoscale rules scale in and reduce the number of VM instances.

若要列出连接到规模集中的 VM 实例所需的 NAT 端口,请先使用 Get-AzureRmLoadBalancer 获取负载均衡器对象,To list the NAT ports to connect to VM instances in a scale set, first get the load balancer object with Get-AzureRmLoadBalancer. 然后使用 Get-AzureRmLoadBalancerInboundNatRuleConfig 查看入站 NAT 规则:Then, view the inbound NAT rules with Get-AzureRmLoadBalancerInboundNatRuleConfig:

# Get the load balancer object
$lb = Get-AzureRmLoadBalancer -ResourceGroupName "myResourceGroup" -Name "myLoadBalancer"

# View the list of inbound NAT rules
Get-AzureRmLoadBalancerInboundNatRuleConfig -LoadBalancer $lb | Select-Object Name,Protocol,FrontEndPort,BackEndPort

以下示例输出显示了实例名称、负载均衡器的公共 IP 地址,以及可以通过 NAT 规则将流量转发到其中的端口号:The following example output shows the instance name, public IP address of the load balancer, and port number that the NAT rules forward traffic to:

Name        Protocol FrontendPort BackendPort
----        -------- ------------ -----------
myRDPRule.0 Tcp             50001        3389
myRDPRule.1 Tcp             50002        3389

此规则的 Name 与以前的 Get-AzureRmVmssVM 命令中显示的 VM 实例的名称相符。The Name of the rule aligns with the name of the VM instance as shown in a previous Get-AzureRmVmssVM command. 例如,若要连接到 VM 实例 0,请使用 myRDPRule.0 并连接到端口 50001For example, to connect to VM instance 0, you use myRDPRule.0 and connect to port 50001. 若要连接到 VM 实例 1,请使用 myRDPRule.1 中的值并连接到端口 50002To connect to VM instance 1, use the value from myRDPRule.1 and connect to port 50002.

使用 Get-AzureRmPublicIpAddress 查看负载均衡器的公共 IP 地址:View the public IP address of the load balancer with Get-AzureRmPublicIpAddress:

Get-AzureRmPublicIpAddress -ResourceGroupName "myResourceGroup" -Name myPublicIP | Select IpAddress

示例输出:Example output:


创建连接到第一个 VM 实例所需的远程连接。Create a remote connection to your first VM instance. 指定所需 VM 实例对应的你自己的公共 IP 地址和端口号,如前述命令所示。Specify your own public IP address and port number of the required VM instance, as shown from the preceding commands. 出现提示时,输入创建规模集时使用的凭据(在示例命令中,默认为 azureuser 和 P@ssw0rd! )。When prompted, enter the credentials used when you created the scale set (by default in the sample commands, they are azureuser and P@ssw0rd!). 以下示例连接到 VM 实例 0The following example connects to VM instance 0:

mstsc /v

登录后,从任务栏打开 Internet Explorer。Once logged in, open Internet Explorer from the taskbar.

  • 选择“确定”,接受“使用推荐的安全性、隐私和兼容性设置”这一提示 。Select OK to accept the prompt to Use recommended security, privacy, and compatibility settings
  • 在地址栏中键入 http://download.sysinternals.com/files/CPUSTRES.zipType http://download.sysinternals.com/files/CPUSTRES.zip in the address bar.
  • 由于 Internet Explorer 增强型安全配置已启用,因此请选择“添加”,以便将 http://download.sysinternals.com 域添加到受信任站点的列表。As Internet Explorer Enhanced Security Configuration is enabled, choose to Add the http://download.sysinternals.com domain to your list of trusted sites.
  • 提示查找下载的文件时,请选择“打开”,然后选择“运行”,以便运行 CPUSTRES.EXE 工具。When prompted for the file download, select Open, then select and Run the CPUSTRES.EXE tool.

若要生成一些 CPU 负载,请勾选“活动”线程所对应的两个框。To generate some CPU load, check two boxes for Active threads. 从两个线程的“活动”下拉菜单中选择“最大”。From the Activity drop-down menu for both threads, select Maximum. 可以打开任务管理器来确认 VM 上的 CPU 负载是否已达到 100%。You can open Task Manager to confirm that the CPU load on the VM is at 100%.

CPU Stress 实用程序可以在 VM 实例上生成负载

让此远程桌面连接会话保持打开状态,打开另一个远程桌面连接会话。Leave the remote desktop connection session open, and open another remote desktop connection session. 连接到第二个 VM 实例,所使用的端口号是在前面的 Get-AzureRmLoadBalancerInboundNatRuleConfig cmdlet 中列出的:Connect to the second VM instance with the port number listed from the previous Get-AzureRmLoadBalancerInboundNatRuleConfig cmdlet:

mstsc /v

登录到第二个 VM 实例以后,重复以前的步骤,以便下载并运行 CPUSTRES.EXEOnce logged in to the second VM instance, repeat the previous steps to download and run CPUSTRES.EXE. 再次启动两个“活动”线程,并将活动设置为“最大”。Again, start two Active threads, and set the activity to Maximum.

请让两个远程桌面连接会话保持打开状态,以便 CPU Stress 工具能够继续运行。To allow the CPU Stress tool to continue running, leave both remote desktop connection sessions open.

监视活动的自动缩放规则Monitor the active autoscale rules

若要监视规模集中的 VM 实例数,请使用 whileTo monitor the number of VM instances in your scale set, use while. 自动缩放规模需要 5 分钟的时间才能启动横向扩展过程,以便响应由每个 VM 实例上的 CPUStress 生成的 CPU 负载:It takes 5 minutes for the autoscale scales to begin the scale out process in response to the CPU load generated by CPUStress on each of the VM instances:

while (1) {Get-AzureRmVmssVM `
    -ResourceGroupName $myResourceGroup `
    -VMScaleSetName $myScaleSet; sleep 10}

达到 CPU 阈值以后,自动缩放规则会增加规模集中的 VM 实例数。Once the CPU threshold has been met, the autoscale rules increase the number of VM instances in the scale set. 以下输出显示,在规模集进行自动横向扩展时创建了 3 个 VM:The following output shows three VMs created as the scale set autoscales out:

ResourceGroupName         Name Location          Sku Capacity InstanceID ProvisioningState
-----------------         ---- --------          --- -------- ---------- -----------------
MYRESOURCEGROUP   myScaleSet_2   chinanorth Standard_DS2                   2         Succeeded
MYRESOURCEGROUP   myScaleSet_3   chinanorth Standard_DS2                   3         Succeeded
MYRESOURCEGROUP   myScaleSet_4   chinanorth Standard_DS2                   4          Creating
MYRESOURCEGROUP   myScaleSet_5   chinanorth Standard_DS2                   5          Creating
MYRESOURCEGROUP   myScaleSet_6   chinanorth Standard_DS2                   6          Creating

在连接到每个 VM 实例的远程桌面连接会话中,关闭 CPU Stress 工具。In your remote desktop connection session to each of your VM instances, close the CPU Stress tool. 此时整个规模集的平均 CPU 负载回到正常。The average CPU load across the scale set returns to normal. 另一个 5 分钟后,自动缩放规则会横向缩减 VM 实例数。After another 5 minutes, the autoscale rules then scale in the number of VM instances. 横向缩减操作会首先删除 ID 值最高的 VM 实例。Scale in actions remove VM instances with the highest IDs first. 如果规模集使用可用性集,则缩减操作将均匀分布到这些 VM 实例上。When a scale set uses Availability Sets, scale in actions are evenly distributed across those VM instances. 以下示例输出显示,在规模集进行自动横向缩减时删除了一个 VM 实例:The following example output shows one VM instance deleted as the scale set autoscales in:

MYRESOURCEGROUP   myScaleSet_6   chinanorth Standard_DS2                   6          Deleting

使用 Ctrl-c 退出 whileExit while with Ctrl-c. 规模集继续每 5 分钟横向缩减一次,每次删除一个 VM 实例,直至达到最小实例计数 2。The scale set continues to scale in every 5 minutes and remove one VM instance until the minimum instance count of two is reached.

清理资源Clean up resources

若要删除规模集和其他资源,请使用 Remove-AzureRmResourceGroup 删除资源组及其所有资源。To remove your scale set and additional resources, delete the resource group and all its resources with Remove-AzureRmResourceGroup. -Force 参数将确认是否希望删除资源,不会显示询问是否删除的额外提示。The -Force parameter confirms that you wish to delete the resources without an additional prompt to do so. -AsJob 参数会使光标返回提示符处,不会等待操作完成。The -AsJob parameter returns control to the prompt without waiting for the operation to complete.

Remove-AzureRmResourceGroup -Name "myResourceGroup" -Force -AsJob

后续步骤Next steps

本教程介绍了如何使用 Azure PowerShell 自动进行规模集的横向缩减或扩展:In this tutorial, you learned how to automatically scale in or out a scale set with Azure PowerShell:

  • 对规模集使用自动缩放Use autoscale with a scale set
  • 创建和使用自动缩放规则Create and use autoscale rules
  • 对 VM 实例进行压力测试并触发自动缩放规则Stress-test VM instances and trigger autoscale rules
  • 在需求下降时自动横向缩减Autoscale back in as demand is reduced