Skip to content

Commit b8e9d27

Browse files
Merge pull request #235482 from EdB-MSFT/autoscale-using-powershell
New Article: Configure autoscale using PowerShell
2 parents ce353ec + e977039 commit b8e9d27

File tree

2 files changed

+319
-2
lines changed

2 files changed

+319
-2
lines changed
Lines changed: 317 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,317 @@
1+
---
2+
title: Configure autoscale using PowerShell
3+
description: Configure autoscale for a Virtual Machine Scale Set using PowerShell
4+
author: EdB-MSFT
5+
ms.author: edbaynash
6+
ms.topic: how-to
7+
ms.date: 01/05/2023
8+
ms.subservice: autoscale
9+
ms.reviewer: akkumari
10+
11+
# Customer intent: As a user or dev ops administrator, I want to use powershell to set up autoscale so I can scale my VMSS.
12+
13+
---
14+
15+
# Configure autoscale with PowerShell
16+
17+
Autoscale settings help ensure that you have the right amount of resources running to handle the fluctuating load of your application. You can configure autoscale using the Azure portal, Azure CLI, PowerShell or ARM or Bicep templates.
18+
19+
This article shows you how to configure autoscale for a Virtual Machine Scale Set with PowerShell, using the following steps:
20+
21+
+ Create a scale set that you can autoscale
22+
+ Create rules to scale in and scale out
23+
+ Create a profile that uses your rules
24+
+ Apply the autoscale settings
25+
+ Update your autoscale settings with notifications
26+
27+
## Prerequisites
28+
29+
To configure autoscale using PowerShell, you need an Azure account with an active subscription. You can [create an account for free](https://azure.microsoft.com/free).
30+
31+
## Set up your environment
32+
33+
```azurepowershell
34+
#Set the subscription Id, VMSS name, and resource group name
35+
$subscriptionId = (Get-AzContext).Subscription.Id
36+
$resourceGroupName="rg-powershell-autoscale"
37+
$vmssName="vmss-001"
38+
```
39+
40+
## Create a Virtual Machine Scale Set
41+
42+
Create a scale set using the following cmdlets. Set the `$resourceGroupName` and `$vmssName` variables to suite your environment.
43+
44+
```azurepowershell
45+
# create a new resource group
46+
New-AzResourceGroup -ResourceGroupName $resourceGroupName -Location "EastUS"
47+
48+
# Create login credentials for the VMSS
49+
$vmPassword = ConvertTo-SecureString "ChangeThisPassword1" -AsPlainText -Force
50+
$vmCred = New-Object System.Management.Automation.PSCredential('azureuser', $vmPassword)
51+
52+
53+
New-AzVmss `
54+
-ResourceGroupName $resourceGroupName `
55+
-Location "EastUS" `
56+
-VMScaleSetName $vmssName `
57+
-Credential $vmCred `
58+
-VirtualNetworkName "myVnet" `
59+
-SubnetName "mySubnet" `
60+
-PublicIpAddressName "myPublicIPAddress" `
61+
-LoadBalancerName "myLoadBalancer" `
62+
-OrchestrationMode "Flexible"
63+
64+
```
65+
66+
## Create autoscale settings
67+
68+
To create autoscale setting using PowerShell, follow the sequence below:
69+
70+
1. Create rules using `New-AzAutoscaleScaleRuleObject`
71+
1. Create a profile using `New-AzAutoscaleProfileObject`
72+
1. Create the autoscale settings using `New-AzAutoscaleSetting`
73+
1. Update the settings using `Update-AzAutoscaleSetting`
74+
75+
### Create rules
76+
77+
Create scale in and scale out rules then associated them with a profile.
78+
Rules are created using the [`New-AzAutoscaleScaleRuleObject`](https://learn.microsoft.com/powershell/module/az.monitor/new-azautoscalescaleruleobject).
79+
80+
The following PowerShell script creates two rules.
81+
82+
+ Scale out when Percentage CPU exceeds 70%
83+
+ Scale in when Percentage CPU is less than 30%
84+
85+
```azurepowershell
86+
87+
$rule1=New-AzAutoscaleScaleRuleObject `
88+
-MetricTriggerMetricName "Percentage CPU" `
89+
-MetricTriggerMetricResourceUri "/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName/providers/Microsoft.Compute/virtualMachineScaleSets/$vmssName" `
90+
-MetricTriggerTimeGrain ([System.TimeSpan]::New(0,1,0)) `
91+
-MetricTriggerStatistic "Average" `
92+
-MetricTriggerTimeWindow ([System.TimeSpan]::New(0,5,0)) `
93+
-MetricTriggerTimeAggregation "Average" `
94+
-MetricTriggerOperator "GreaterThan" `
95+
-MetricTriggerThreshold 70 `
96+
-MetricTriggerDividePerInstance $false `
97+
-ScaleActionDirection "Increase" `
98+
-ScaleActionType "ChangeCount" `
99+
-ScaleActionValue 1 `
100+
-ScaleActionCooldown ([System.TimeSpan]::New(0,5,0))
101+
102+
103+
$rule2=New-AzAutoscaleScaleRuleObject `
104+
-MetricTriggerMetricName "Percentage CPU" `
105+
-MetricTriggerMetricResourceUri "/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName/providers/Microsoft.Compute/virtualMachineScaleSets/$vmssName" `
106+
-MetricTriggerTimeGrain ([System.TimeSpan]::New(0,1,0)) `
107+
-MetricTriggerStatistic "Average" `
108+
-MetricTriggerTimeWindow ([System.TimeSpan]::New(0,5,0)) `
109+
-MetricTriggerTimeAggregation "Average" `
110+
-MetricTriggerOperator "LessThan" `
111+
-MetricTriggerThreshold 30 `
112+
-MetricTriggerDividePerInstance $false `
113+
-ScaleActionDirection "Decrease" `
114+
-ScaleActionType "ChangeCount" `
115+
-ScaleActionValue 1 `
116+
-ScaleActionCooldown ([System.TimeSpan]::New(0,5,0))
117+
```
118+
The table below describes the parameters used in the `New-AzAutoscaleScaleRuleObject` cmdlet.
119+
120+
|Parameter| Description|
121+
|---|---|
122+
|`MetricTriggerMetricName` |Sets the autoscale trigger metric
123+
|`MetricTriggerMetricResourceUri`| Specifies the resource that the `MetricTriggerMetricName` metric belongs to. `MetricTriggerMetricResourceUri` can be any resource and not just the resource that's being scaled. For example, you can scale your Virtual Machine Scale Sets based on metrics created by a load balancer, database, or the scale set itself. The `MetricTriggerMetricName` must exist for the specified `MetricTriggerMetricResourceUri`.
124+
|`MetricTriggerTimeGrain`|The sampling frequency of the metric that the rule monitors. `MetricTriggerTimeGrain` must be one of the predefined values for the specified metric and must be between 12 hours and 1 minute. For example, `MetricTriggerTimeGrain` = *PT1M*"* means that the metrics are sampled every 1 minute and aggregated using the aggregation method specified in `MetricTriggerStatistic`.
125+
|`MetricTriggerTimeAggregation` | The aggregation method within the timeGrain period. For example, statistic = "Average" and timeGrain = "PT1M" means that the metrics are aggregated every 1 minute by taking the average.
126+
|`MetricTriggerStatistic` |The aggregation method used to aggregate the sampled metrics. For example, TimeAggregation = "Average" aggregates the sampled metrics by taking the average.
127+
|`MetricTriggerTimeWindow` | The amount of time that the autoscale engine looks back to aggregate the metric. This value must be greater than the delay in metric collection, which varies by resource. It must be between 5 minutes and 12 hours. For example, 10 minutes means that every time autoscale runs, it queries metrics for the past 10 minutes. This feature allows your metrics to stabilize and avoids reacting to transient spikes.
128+
|`MetricTriggerThreshold`|Defines the value of the metric that triggers a scale event.
129+
|`MetricTriggerOperator` |Specifies the logical comparative operating to use when evaluating the metric value.
130+
|`MetricTriggerDividePerInstance`| When set to `true` divides the trigger metric by the total number of instances. For example, If message count is 300 and there are 5 instances running, the calculated metric value is 60 messages per instance. This property isn't applicable for all metrics.
131+
| `ScaleActionDirection`| Specify scaling in or out. Valid values are `Increase` and `Decrease`.
132+
|`ScaleActionType` |Scale by a specific number of instances, scale to a specific instance count, or scale by percentage of the current instance count. Valid values include `ChangeCount`, `ExactCount`, and `PercentChangeCount`.
133+
|`ScaleActionCooldown`| The minimum amount of time to wait between scale operations. This is to allow the metrics to stabilize and avoids [flapping](./autoscale-flapping.md). For example, if `ScaleActionCooldown` is 10 minutes and a scale operation just occurred, Autoscale won't attempt to scale again for 10 minutes.
134+
135+
136+
### Create a default autoscale profile and associate the rules
137+
138+
After defining the scale rules, create a profile. The profile specifies the default, upper, and lower instance count limits, and the times that the associated rules can be applied. Use the [`New-AzAutoscaleProfileObject`](https://learn.microsoft.com/powershell/module/az.monitor/new-azautoscaleprofileobject) cmdlet to create a new autoscale profile. As this is a default profile, it doesn't have any schedule parameters. The default profile is active at times that no other profiles are active
139+
140+
```azurepowershell
141+
$defaultProfile=New-AzAutoscaleProfileObject `
142+
-Name "default" `
143+
-CapacityDefault 1 `
144+
-CapacityMaximum 10 `
145+
-CapacityMinimum 1 `
146+
-Rule $rule1, $rule2
147+
```
148+
149+
The table below describes the parameters used in the `New-AzAutoscaleProfileObject` cmdlet.
150+
151+
|Parameter|Description|
152+
|---|---|
153+
|`CapacityDefault`| The number of instances that are if metrics aren't available for evaluation. The default is only used if the current instance count is lower than the default.
154+
| `CapacityMaximum` |The maximum number of instances for the resource. The maximum number of instances is further limited by the number of cores that are available in the subscription.
155+
| `CapacityMinimum` |The minimum number of instances for the resource.
156+
|`FixedDateEnd`| The end time for the profile in ISO 8601 format for.
157+
|`FixedDateStart` |The start time for the profile in ISO 8601 format.
158+
| `Rule` |A collection of rules that provide the triggers and parameters for the scaling action when this profile is active. A maximum of 10, comma separated rules can be specified.
159+
|`RecurrenceFrequency` | How often the scheduled profile takes effect. This value must be `week`.
160+
|`ScheduleDay`| A collection of days that the profile takes effect on when specifying a recurring schedule. Possible values are Sunday through Saturday. For more information on recurring schedules, see [Add a recurring profile using CLI](./autoscale-multiprofile.md?tabs=powershell#add-a-recurring-profile-using-powershell)
161+
|`ScheduleHour`| A collection of hours that the profile takes effect on. Values supported are 0 to 23.
162+
|`ScheduleMinute`| A collection of minutes at which the profile takes effect.
163+
|`ScheduleTimeZone` |The timezone for the hours of the profile.
164+
165+
### Apply the autoscale settings
166+
167+
After fining the rules and profile, apply the autoscale settings using [`New-AzAutoscaleSetting`](https://learn.microsoft.com/powershell/module/az.monitor/new-azautoscalesetting). To update existing autoscale setting use [`Update-AzAutoscaleSetting`](https://learn.microsoft.com/powershell/module/az.monitor/add-azautoscalesetting)
168+
169+
```azurepowershell
170+
New-AzAutoscaleSetting `
171+
-Name vmss-autoscalesetting1 `
172+
-ResourceGroupName $resourceGroupName `
173+
-Location eastus `
174+
-Profile $defaultProfile `
175+
-Enabled `
176+
-PropertiesName "vmss-autoscalesetting1" `
177+
-TargetResourceUri "/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName/providers/Microsoft.Compute/virtualMachineScaleSets/$vmssName"
178+
```
179+
180+
### Add notifications to your autoscale settings
181+
182+
Add notifications to your sale setting to trigger a webhook or send email notifications when a scale event occurs.
183+
For more information on webhook notifications, see [`New-AzAutoscaleWebhookNotificationObject`](https://learn.microsoft.com/powershell/module/az.monitor/new-azautoscalewebhooknotificationobject)
184+
185+
Set a webhook using the following cmdlet;
186+
```azurepowershell
187+
188+
$webhook1=New-AzAutoscaleWebhookNotificationObject -Property @{} -ServiceUri "http://contoso.com/webhook1"
189+
```
190+
191+
Configure the notification using the webhook and set up email notification using the [`New-AzAutoscaleNotificationObject`](https://learn.microsoft.com/powershell/module/az.monitor/new-azautoscalenotificationobject) cmdlet:
192+
193+
```azurepowershell
194+
195+
$notification1=New-AzAutoscaleNotificationObject `
196+
-EmailCustomEmail "[email protected]" `
197+
-EmailSendToSubscriptionAdministrator $true `
198+
-EmailSendToSubscriptionCoAdministrator $true `
199+
-Webhook $webhook1
200+
```
201+
202+
Update your autoscale settings to apply the notification
203+
204+
```azurepowershell
205+
206+
Update-AzAutoscaleSetting `
207+
-Name vmss-autoscalesetting1 `
208+
-ResourceGroupName $resourceGroupName `
209+
-Profile $defaultProfile `
210+
-Notification $notification1 `
211+
-TargetResourceUri "/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName/providers/Microsoft.Compute/virtualMachineScaleSets/$vmssName"
212+
213+
```
214+
215+
## Review your autoscale settings
216+
217+
To review your autoscale settings, load the settings into a variable using `Get-AzAutoscaleSetting` then output the variable as follows:
218+
219+
```azurepowershell
220+
$autoscaleSetting=Get-AzAutoscaleSetting -ResourceGroupName $resourceGroupName -Name vmss-autoscalesetting1
221+
$autoscaleSetting | Select-Object -Property *
222+
```
223+
224+
Get your autoscale history using `AzAutoscaleHistory`
225+
```azurepowershell
226+
Get-AzAutoscaleHistory -ResourceId /subscriptions/<subscriptionId/resourceGroups/$resourceGroupName/providers/Microsoft.Compute/virtualMachineScaleSets/$vmssName
227+
```
228+
229+
## Scheduled and recurring profiles
230+
231+
### Add a scheduled profile for a special event
232+
233+
Set up autoscale profiles to scale differently for specific events. For example, for a day when demand will be higher than usual, create a profile with increased maximum and minimum instance limits.
234+
235+
The following example uses the same rules as the default profile defined above, but sets new instance limits for a specific date. You can also configure different rules to be used with the new profile.
236+
237+
```azurepowershell
238+
$highDemandDay=New-AzAutoscaleProfileObject `
239+
-Name "High-demand-day" `
240+
-CapacityDefault 7 `
241+
-CapacityMaximum 30 `
242+
-CapacityMinimum 5 `
243+
-FixedDateEnd ([System.DateTime]::Parse("2023-12-31T14:00:00Z")) `
244+
-FixedDateStart ([System.DateTime]::Parse("2023-12-31T13:00:00Z")) `
245+
-FixedDateTimeZone "UTC" `
246+
-Rule $rule1, $rule2
247+
248+
Update-AzAutoscaleSetting `
249+
-Name vmss-autoscalesetting1 `
250+
-ResourceGroupName $resourceGroupName `
251+
-Profile $defaultProfile, $highDemandDay `
252+
-Notification $notification1 `
253+
-TargetResourceUri "/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName/providers/Microsoft.Compute/virtualMachineScaleSets/$vmssName"
254+
255+
```
256+
257+
### Add a recurring scheduled profile
258+
259+
Recurring profiles let you schedule a scaling profile that repeats each week. For example, scale to a single instance on the weekend from Friday night to Monday morning.
260+
261+
While scheduled profiles have a start and end date, recurring profiles don't have an end time. A profile remains active until the next profile's start time. Therefore, when you create a recurring profile you must create a recurring default profile that starts when you want the previous recurring profile to finish.
262+
263+
For example, to configure a weekend profile that starts on Friday nights and ends on Monday mornings, create a profile that starts on Friday night, then create recurring profile with your default settings that starts on Monday morning.
264+
265+
The following script creates a weekend profile and an addition default profile to end the weekend profile.
266+
```azurepowershell
267+
$fridayProfile=New-AzAutoscaleProfileObject `
268+
-Name "Weekend" `
269+
-CapacityDefault 1 `
270+
-CapacityMaximum 1 `
271+
-CapacityMinimum 1 `
272+
-RecurrenceFrequency week `
273+
-ScheduleDay "Friday" `
274+
-ScheduleHour 22 `
275+
-ScheduleMinute 00 `
276+
-ScheduleTimeZone "Pacific Standard Time" `
277+
-Rule $rule1, $rule2
278+
279+
280+
$defaultRecurringProfile=New-AzAutoscaleProfileObject `
281+
-Name "default recurring profile" `
282+
-CapacityDefault 2 `
283+
-CapacityMaximum 10 `
284+
-CapacityMinimum 2 `
285+
-RecurrenceFrequency week `
286+
-ScheduleDay "Monday" `
287+
-ScheduleHour 00 `
288+
-ScheduleMinute 00 `
289+
-ScheduleTimeZone "Pacific Standard Time" `
290+
-Rule $rule1, $rule2
291+
292+
New-AzAutoscaleSetting `
293+
-Location eastus `
294+
-Name vmss-autoscalesetting1 `
295+
-ResourceGroupName $resourceGroupName `
296+
-Profile $defaultRecurringProfile, $fridayProfile `
297+
-Notification $notification1 `
298+
-TargetResourceUri "/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName/providers/Microsoft.Compute/virtualMachineScaleSets/$vmssName"
299+
300+
```
301+
302+
For more information on scheduled profiles, see [Autoscale with multiple profiles](./autoscale-multiprofile.md)
303+
304+
## Other autoscale commands
305+
306+
For a complete list of PowerShell cmdlets for autoscale, see the [PowerShell Module Browser](https://learn.microsoft.com/powershell/module/?term=azautoscale)
307+
308+
## Clean up resources
309+
310+
To clean up the resources you created in this tutorial, delete the resource group that you created.
311+
The following cmdlet deletes the resource group and all of its resources.
312+
```azurecli
313+
314+
Remove-AzResourceGroup -Name $resourceGroupName
315+
316+
```
317+

articles/azure-monitor/toc.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1435,12 +1435,12 @@ items:
14351435
href: autoscale/autoscale-common-scale-patterns.md
14361436
- name: Scale with custom metrics
14371437
href: autoscale/autoscale-custom-metric.md
1438+
- name: Autoscale Virtual Machine Scale Sets using PowerShell
1439+
href: autoscale/autoscale-using-powershell.md
14381440
- name: Scale Virtual Machine Scale Sets using Resource Manager templates
14391441
href: ../virtual-machine-scale-sets/tutorial-autoscale-template.md?toc=/azure/azure-monitor/toc.json
14401442
- name: Scale Virtual Machine Scale Sets using CLI
14411443
href: ../virtual-machine-scale-sets/tutorial-autoscale-cli.md?toc=/azure/azure-monitor/toc.json
1442-
- name: Scale Virtual Machine Scale Sets using PowerShell
1443-
href: ../virtual-machine-scale-sets/tutorial-autoscale-powershell.md?toc=/azure/azure-monitor/toc.json
14441444
- name: Use webhooks and email notifications
14451445
href: autoscale/autoscale-webhook-email.md
14461446
- name: Autoscale diagnostics

0 commit comments

Comments
 (0)