Azure / Azure/azure-powershell

New-AzAutoscaleSetting throws convaluted error if an autoscale rule has an invalid metric name.

Open
#24,727 2 comments 0 reactions 0 assignees View on GitHub
act-observability-squad Azure PS Team bug customer-reported Monitor - Autoscale Tracking
Dominant language
C#
Stars
4.8k
Forks
4.3k
Avg merge
3d 14h
Merged PRs (30d)
54

Description

### Description

Using the Autoscale for an App Service Plan:
If using New-AzAutoscaleScaleRuleObject -MetricTriggerMetricName "Percentage CPU" (as per the example on your website: https://learn.microsoft.com/en-us/powershell/module/az.monitor/new-azautoscalescaleruleobject?view=azps-11.5.0) no error is thrown for the rule, or when setting the profile. A convaluted unhandled exception is thrown for the New-AzAutoscaleSetting when using this rule (and profile), which does not indicate what the problem is.

I do not know where to find the list of valid metric names, so I created an autoscale setting manually and examined the properties.

FYI: The metric name should be: "CpuPercentage", then the script will work fine.

Note: in the error log below, it is HistoryId 7 that I see. HistoryId 5 was a previous run that I forgot to set $AutoScaleName

### Issue script & Debug output

```PowerShell
$newASP = New-AzAppServicePlan -Name $newASPName -Location $DataCenterLocation -ResourceGroupName $ResourceGroupName -Tier $ASPTier -NumberofWorkers 1 -WorkerSize $ASPSize -ErrorAction Stop
$AspId = $newASP.Id

$ScaleOutRule1 = New-AzAutoscaleScaleRuleObject -MetricTriggerMetricResourceUri $AspId -MetricTriggerMetricName "Percentage CPU" -MetricTriggerMetricNamespace "microsoft.web/serverfarms" -MetricTriggerStatistic "Average" -MetricTriggerTimeAggregation "Average" -MetricTriggerOperator "GreaterThan" `
-MetricTriggerThreshold 90 -ScaleActionDirection "Increase" -ScaleActionType "ChangeCount" -ScaleActionValue 1 -ScaleActionCooldown([System.TimeSpan]::New(0,10,0)) -MetricTriggerTimeGrain ([System.TimeSpan]::New(0,1,0)) -MetricTriggerTimeWindow ([System.TimeSpan]::New(0,5,0)) -ErrorAction Stop

$ScaleInRule1 = New-AzAutoscaleScaleRuleObject -MetricTriggerMetricResourceUri $AspId -MetricTriggerMetricName "Percentage CPU" -MetricTriggerMetricNamespace "microsoft.web/serverfarms" -MetricTriggerStatistic "Average" -MetricTriggerTimeAggregation "Average" -MetricTriggerOperator "LessThanOrEqual" `
-MetricTriggerThreshold 70 -ScaleActionDirection "Decrease" -ScaleActionType "ChangeCount" -ScaleActionValue 1 -ScaleActionCooldown ([System.TimeSpan]::New(0,10,0)) -MetricTriggerTimeGrain ([System.TimeSpan]::New(0,1,0)) -MetricTriggerTimeWindow ([System.TimeSpan]::New(0,5,0)) -ErrorAction Stop

$ScaleNotification = New-AzAutoscaleNotificationObject -EmailCustomEmail $CustomScaleNotificationEmails -EmailSendToSubscriptionAdministrator $false -EmailSendToSubscriptionCoAdministrator $false

$AutoScaleProfile1 = New-AzAutoscaleProfileObject -Name "Normal Scaling During Business Hours" -CapacityDefault "1" -CapacityMaximum "10" -CapacityMinimum "1" `
-Rule $ScaleOutRule1, $ScaleInRule1 -RecurrenceFrequency Week -ScheduleDay "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" `
-ScheduleHour 06 -ScheduleMinute 00 -ScheduleTimeZone $TimeZone -ErrorAction Stop

New-AzAutoscaleSetting -Name $AutoScaleName -Location $DataCenterLocation -ResourceGroupName $ResourceGroupName -TargetResourceUri $AspId -Profile $AutoScaleProfile1 -Enabled -Notification $ScaleNotification
```

### Environment data

```PowerShell
Name Value
---- -----
PSVersion 7.4.1
PSEdition Core
GitCommitId 7.4.1
OS Microsoft Windows 10.0.22631
Platform Win32NT
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0
```

### Module versions

```PowerShell
ModuleType Version PreRelease Name PSEdition ExportedCommands
---------- ------- ---------- ---- --------- ----------------
Script 11.5.0 Az Core,Desk
Script 2.17.0 Az.Accounts Core,Desk {Disable-AzDataCollection, Disable-AzCo…
Script 2.0.0 Az.Advisor Core,Desk {Disable-AzAdvisorRecommendation, Enabl…
Script 6.0.2 Az.Aks Core,Desk {Disable-AzAksAddOn, Enable-AzAksAddOn,…
Script 1.1.4 Az.AnalysisServices Core,Desk {Resume-AzAnalysisServicesServer, Suspe…
Script 4.0.2 Az.ApiManagement Core,Desk {Add-AzApiManagementApiToGateway, Add-A…
Script 1.0.0 Az.App Core,Desk {Disable-AzContainerAppRevision, Enable…
Script 1.3.0 Az.AppConfiguration Core,Desk {Get-AzAppConfigurationStore, Get-AzApp…
Script 2.2.4 Az.ApplicationInsights Core,Desk {Get-AzApplicationInsights, Get-AzAppli…
Script 1.0.0 Az.ArcResourceBridge Core,Desk {Get-AzArcResourceBridge, Get-AzArcReso…
Script 2.0.1 Az.Attestation Core,Desk {Add-AzAttestationPolicySigner, Get-AzA…
Script 1.0.0 Az.Automanage Core,Desk {Get-AzAutomanageBestPractice, Get-AzAu…
Script 1.10.0 Az.Automation Core,Desk {Export-AzAutomationDscConfiguration, E…
Script 3.5.0 Az.Batch Core,Desk {Remove-AzBatchAccount, Get-AzBatchAcco…
Script 2.0.3 Az.Billing Core,Desk {Get-AzBillingInvoice, Get-AzBillingPer…
Script 3.1.2 Az.Cdn Core,Desk {Clear-AzCdnEndpointContent, Clear-AzFr…
Script 2.0.0 Az.CloudService Core,Desk {Get-AzCloudService, Get-AzCloudService…
Script 1.14.1 Az.CognitiveServices Core,Desk {Get-AzCognitiveServicesAccount, Get-Az…
Script 7.2.0 Az.Compute Core,Desk {Add-AzImageDataDisk, Add-AzVhd, Add-Az…
Script 1.0.0 Az.ConfidentialLedger Core,Desk {Get-AzConfidentialLedger, New-AzConfid…
Script 4.0.0 Az.ContainerInstance Core,Desk {Add-AzContainerInstanceOutput, Get-AzC…
Script 4.2.0 Az.ContainerRegistry Core,Desk {Connect-AzContainerRegistry, Get-AzCon…
Script 1.14.2 Az.CosmosDB Core,Desk {Get-AzCosmosDBAccount, Get-AzCosmosDBA…
Script 1.1.0 Az.DataBoxEdge Core,Desk {Get-AzDataBoxEdgeJob, Get-AzDataBoxEdg…
Script 1.7.1 Az.Databricks Core,Desk {Get-AzDatabricksAccessConnector, Get-A…
Script 1.18.3 Az.DataFactory Core,Desk {Add-AzDataFactoryV2DataFlowDebugSessio…
Script 1.0.3 Az.DataLakeAnalytics Core,Desk {Get-AzDataLakeAnalyticsDataSource, New…
Script 1.3.0 Az.DataLakeStore Core,Desk {Get-AzDataLakeStoreTrustedIdProvider, …
Script 2.3.0 Az.DataProtection Core,Desk {Backup-AzDataProtectionBackupInstanceA…
Script 1.0.1 Az.DataShare Core,Desk {New-AzDataShareAccount, Get-AzDataShar…
Script 4.3.0 Az.DesktopVirtualization Core,Desk {Disconnect-AzWvdUserSession, Expand-Az…
Script 1.1.0 Az.DevCenter Core,Desk {Deploy-AzDevCenterUserEnvironment, Get…
Script 1.0.2 Az.DevTestLabs Core,Desk {Get-AzDtlAllowedVMSizesPolicy, Get-AzD…
Script 1.2.0 Az.Dns Core,Desk {Get-AzDnsRecordSet, New-AzDnsRecordCon…
Script 1.0.1 Az.ElasticSan Core,Desk {Add-AzElasticSanVolumeGroupNetworkRule…
Script 1.6.1 Az.EventGrid Core,Desk {Enable-AzEventGridPartnerTopic, Get-Az…
Script 4.2.1 Az.EventHub Core,Desk {New-AzEventHubAuthorizationRuleSASToke…
Script 1.10.0 Az.FrontDoor Core,Desk {New-AzFrontDoor, Get-AzFrontDoor, Set-…
Script 4.0.7 Az.Functions Core,Desk {Get-AzFunctionApp, Get-AzFunctionAppAv…
Script 6.1.0 Az.HDInsight Core,Desk {Add-AzHDInsightClusterIdentity, Add-Az…
Script 2.0.0 Az.HealthcareApis Core,Desk {Get-AzHealthcareApisService, Get-AzHea…
Script 2.7.5 Az.IotHub Core,Desk {Add-AzIotHubKey, Get-AzIotHubEventHubC…
Script 5.2.2 Az.KeyVault Core,Desk {Add-AzKeyVaultCertificate, Add-AzKeyVa…
Script 2.3.0 Az.Kusto Core,Desk {Add-AzKustoClusterLanguageExtension, A…
Script 1.0.0 Az.LoadTesting Core,Desk {Get-AzLoad, New-AzLoad, Remove-AzLoad,…
Script 1.5.1 Az.LogicApp Core,Desk {Get-AzIntegrationAccount, Get-AzIntegr…
Script 1.1.3 Az.MachineLearning Core,Desk {Move-AzMlCommitmentAssociation, Get-Az…
Script 1.0.0 Az.MachineLearningServices Core,Desk {Get-AzMLServiceQuota, Get-AzMLServiceU…
Script 1.4.1 Az.Maintenance Core,Desk {Get-AzApplyUpdate, Get-AzConfiguration…
Script 1.2.0 Az.ManagedServiceIdentity Core,Desk {Get-AzSystemAssignedIdentity, Get-AzUs…
Script 3.0.0 Az.ManagedServices Core,Desk {Get-AzManagedServicesAssignment, Get-A…
Script 2.0.0 Az.MarketplaceOrdering Core,Desk {Get-AzMarketplaceTerms, Invoke-AzMarke…
Script 1.1.2 Az.Media Core,Desk {Sync-AzMediaServiceStorageKey, Set-AzM…
Script 2.3.0 Az.Migrate Core,Desk {Get-AzMigrateDiscoveredServer, Get-AzM…
Script 5.1.1 Az.Monitor Core,Desk {Add-AzLogProfile, Add-AzMetricAlertRul…
Script 1.1.1 Az.MySql Core,Desk {Get-AzMySqlConfiguration, Get-AzMySqlC…
Script 7.4.1 Az.Network Core,Desk {Add-AzApplicationGatewayAuthentication…
Script 1.0.0 Az.NetworkCloud Core,Desk {Deploy-AzNetworkCloudCluster, Disable-…
Script 1.0.0 Az.Nginx Core,Desk {Get-AzNginxCertificate, Get-AzNginxCon…
Script 1.1.2 Az.NotificationHubs Core,Desk {Get-AzNotificationHub, Get-AzNotificat…
Script 3.2.0 Az.OperationalInsights Core,Desk {New-AzOperationalInsightsAzureActivity…
Script 1.6.5 Az.PolicyInsights Core,Desk {Get-AzPolicyAttestation, Get-AzPolicyE…
Script 1.1.0 Az.PostgreSql Core,Desk {Get-AzPostgreSqlConfiguration, Get-AzP…
Script 2.0.0 Az.PowerBIEmbedded Core,Desk {Resume-AzPowerBIEmbeddedCapacity, Susp…
Script 1.0.4 Az.PrivateDns Core,Desk {Get-AzPrivateDnsZone, Remove-AzPrivate…
Script 6.8.0 Az.RecoveryServices Core,Desk {Add-AzRecoveryServicesAsrReplicationPr…
Script 1.9.0 Az.RedisCache Core,Desk {Export-AzRedisCache, Get-AzRedisCache,…
Script 1.2.0 Az.RedisEnterpriseCache Core,Desk {Export-AzRedisEnterpriseCache, Get-AzR…
Script 2.0.0 Az.Relay Core,Desk {Get-AzRelayAuthorizationRule, Get-AzRe…
Script 1.2.0 Az.ResourceMover Core,Desk {Add-AzResourceMoverMoveResource, Get-A…
Script 6.16.1 Az.Resources Core,Desk {Export-AzResourceGroup, Export-AzTempl…
Script 1.6.1 Az.Security Core,Desk {Add-AzSecurityAdaptiveNetworkHardening…
Script 3.1.1 Az.SecurityInsights Core,Desk {Get-AzSentinelAlertRule, Get-AzSentine…
Script 3.1.0 Az.ServiceBus Core,Desk {New-AzServiceBusAuthorizationRuleSASTo…
Script 3.3.2 Az.ServiceFabric Core,Desk {Add-AzServiceFabricClientCertificate, …
Script 2.0.0 Az.SignalR Core,Desk {New-AzSignalR, Get-AzSignalR, Get-AzSi…
Script 4.14.0 Az.Sql Core,Desk {Add-AzSqlDatabaseToFailoverGroup, Add-…
Script 2.2.0 Az.SqlVirtualMachine Core,Desk {Get-AzAvailabilityGroupListener, Get-A…
Script 2.3.1 Az.StackHCI Core,Desk {Add-AzStackHCIVMAttestation, Disable-A…
Script 1.0.2 Az.StackHCIVM Core,Desk {Add-AzStackHCIVMVirtualMachineDataDisk…
Script 6.1.3 Az.Storage Core,Desk {Add-AzRmStorageContainerLegalHold, Add…
Script 1.3.0 Az.StorageMover Core,Desk {Get-AzStorageMover, Get-AzStorageMover…
Script 2.1.1 Az.StorageSync Core,Desk {Get-AzStorageSyncCloudEndpoint, Get-Az…
Script 2.0.0 Az.StreamAnalytics Core,Desk {Get-AzStreamAnalyticsCluster, Get-AzSt…
Script 1.0.1 Az.Support Core,Desk {Get-AzSupportProblemClassification, Ge…
Script 3.0.6 Az.Synapse Core,Desk {Add-AzSynapseDataFlowDebugSessionPacka…
Script 1.2.2 Az.TrafficManager Core,Desk {Add-AzTrafficManagerCustomHeaderToEndp…
Script 3.2.0 Az.Websites Core,Desk {Add-AzWebAppAccessRestrictionRule, Add…
S
```

### Error output

```PowerShell
HistoryId: 7

Message : resource: /subscriptions/46a25c82-b36c-4269-a2e3-9f5bef8177e9/resourceGroups/TProCWAppServicePlans/providers/Microsoft.Web/serverfarms/asp-cw6-r1-canadacentral-1, metricnamespace: microsoft.web/serverfarms, metricname: Percentage CPU
StackTrace :
Exception : Microsoft.Azure.PowerShell.Cmdlets.Monitor.Autoscale.Runtime.RestException`1[Microsoft.Azure.PowerShell.Cmdlets.Monitor.Autoscale.Models.Api20221001.IAutoscaleErrorResponse]
InvocationInfo : {New-AzAutoscaleSetting_CreateExpanded}
Line : $scriptCmd = {& $wrappedCmd @PSBoundParameters}

Position : At C:\Program Files\PowerShell\Modules\Az.Monitor\5.1.1\Autoscale.Autorest\exports\ProxyCmdletDefinitions.ps1:768 char:23
+ $scriptCmd = {& $wrappedCmd @PSBoundParameters}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
HistoryId : 7

HistoryId: 5

Message : Cannot bind argument to parameter 'Name' because it is an empty string.
StackTrace : at System.Management.Automation.ParameterBinderBase.ValidateNullOrEmptyArgument(CommandParameterInternal parameter, CompiledCommandParameter parameterMetadata, Type argumentType, Object parameterValue, Boolean recurseIntoCollections)
at System.Management.Automation.ParameterBinderBase.BindParameter(CommandParameterInternal parameter, CompiledCommandParameter parameterMetadata, ParameterBindingFlags flags)
at System.Management.Automation.CmdletParameterBinderController.BindParameter(CommandParameterInternal argument, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags)
at System.Management.Automation.CmdletParameterBinderController.BindParameter(UInt32 parameterSets, CommandParameterInternal argument, MergedCompiledCommandParameter parameter, ParameterBindingFlags flags)
at System.Management.Automation.CmdletParameterBinderController.BindNamedParameter(UInt32 parameterSets, CommandParameterInternal argument, MergedCompiledCommandParameter parameter)
at System.Management.Automation.ParameterBinderController.BindNamedParameters(UInt32 parameterSets, Collection`1 arguments)
at System.Management.Automation.CmdletParameterBinderController.BindCommandLineParametersNoValidation(Collection`1 arguments)
at System.Management.Automation.CmdletParameterBinderController.BindCommandLineParameters(Collection`1 arguments)
at System.Management.Automation.CommandProcessor.BindCommandLineParameters()
at System.Management.Automation.CommandProcessor.Prepare(IDictionary psDefaultParameterValues)
at System.Management.Automation.CommandProcessorBase.DoPrepare(IDictionary psDefaultParameterValues)
at System.Management.Automation.Internal.PipelineProcessor.Start(Boolean incomingStream)
at System.Management.Automation.Internal.PipelineProcessor.SynchronousExecuteEnumerate(Object input)
--- End of stack trace from previous location ---
at System.Management.Automation.Internal.PipelineProcessor.SynchronousExecuteEnumerate(Object input)
at System.Management.Automation.PipelineOps.InvokePipeline(Object input, Boolean ignoreInput, CommandParameterInternal[][] pipeElements, CommandBaseAst[] pipeElementAsts, CommandRedirection[][] commandRedirections, FunctionContext funcContext)
at System.Management.Automation.Interpreter.ActionCallInstruction`6.Run(InterpretedFrame frame)
at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
Exception : System.Management.Automation.ParameterBindingValidationException
InvocationInfo : {New-AzAutoscaleSetting}
Line : New-AzAutoscaleSetting -Name $AutoScaleName -Location $DataCenterLocation -ResourceGroupName $ResourceGroupName -TargetResourceUri $AspId -Profile $AutoScaleProfile1 -Enabled -Notification $ScaleNotification

Position : At line:1 char:30
+ New-AzAutoscaleSetting -Name $AutoScaleName -Location $DataCenterLoca …
+ ~~~~~~~~~~~~~~
HistoryId : 5

HistoryId: 1

Message : Run Connect-AzAccount to login.
StackTrace : at Microsoft.Azure.Commands.ResourceManager.Common.AzureRMCmdlet.get_DefaultContext()
at Microsoft.Azure.Commands.Profile.SetAzureRMContextCommand.ExecuteCmdlet()
at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.<>c__3`1.b__3_0(T c)
at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.ExecuteSynchronouslyOrAsJob[T](T cmdlet, Action`1 executor)
at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.ExecuteSynchronouslyOrAsJob[T](T cmdlet)
at Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ProcessRecord()
Exception : System.Management.Automation.PSInvalidOperationException
InvocationInfo : {Set-AzContext}
Line : $null = Set-AzContext -TenantId $PortalTenantId -SubscriptionId $PortalSubscriptionId -ErrorAction Stop

Position : At X:\ClockWorkCloudDev\Scripts_v6.23.5\CWPSModules\AzureFunctions\AzureFunctions.psm1:6 char:17
+ … $null = Set-AzContext -TenantId $PortalTenantId -SubscriptionId $ …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
HistoryId : 1
```

Contributor guide

Open the contributing guide

Research direction

Start with the New-AzAutoscaleSetting and New-AzAutoscaleScaleRuleObject entry points and reproduce the script using the invalid "Percentage CPU" metric name. Trace how the metric is validated or returned by Azure, then add coverage for an actionable error while preserving successful use of "CpuPercentage".

Written by the indexing model from the issue text.

Assessment

Tech stack
azure, csharp, powershell
Domain
cloud, infrastructure
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
52/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.