Azure PowerShellを使用して自動スケールを構成する

自動スケーリングにより、アプリケーションの変動する負荷に対応するために、適切な量のリソースが確実に実行されます。 自動スケールは、Azure ポータル、Azure CLI、Azure PowerShell、または ARM またはBicep テンプレートを使用して構成できます。

この記事では、PowerShell を使用して仮想マシン スケール セットの自動スケーリングを構成する方法について説明します。 構成では、次の手順を使用します:

  • 自動スケーリングできるスケール セットを作成します。
  • スケールインおよびスケールアウトするルールを作成します。
  • あなたのルールを使用するプロファイルを作成します。
  • 自動スケール設定を適用します。
  • 通知付きの自動スケール設定を更新します。

前提条件

PowerShell を使用して自動スケーリングを構成するには、アクティブなサブスクリプションが含まれる Azure アカウントが必要です。 無料でアカウントを作成できます。

環境を設定する

Note

目的のサブスクリプションを選択して、同じ PowerShell セッションで例を実行します。

# Set variables
$resourceGroupName = "<ResourceGroupName>"
$vmssName = "<VirtualMachineScaleSetName>"
$autoscaleName = "<AutoscaleSettingName>"
$azureRegion = "<AzureRegion>"
$virtualNetworkName = "<VirtualNetworkName>"
$subnetName = "<SubnetName>"
$publicIpAddressName = "<PublicIpAddressName>"
$loadBalancerName = "<LoadBalancerName>"

# Get the subscription ID from the current Azure PowerShell context
$subscriptionId = (Get-AzContext).Subscription.Id

# Build virtual machine scale set resource ID
$vmssPath = "/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName"
$vmssProvider = "Microsoft.Compute/virtualMachineScaleSets/$vmssName"
$vmssResourceId = "$vmssPath/providers/$vmssProvider"

仮想マシン スケール セットの作成

次のAzure PowerShell例では、New-AzResourceGroupコマンドレットとNew-AzVmssコマンドレットを使用します。

Note

作業が終わったらそのリソースを削除できるように、この例では専用のリソース グループを使用します。

この例では、パブリック IP アドレスを作成します。 管理アクセスには、RDP または SSH ポートをインターネットに公開するのではなく、Azure Bastionを使用します。

# Create the resource group
New-AzResourceGroup -ResourceGroupName $resourceGroupName -Location $azureRegion

# Get credentials for the virtual machine scale set
$vmCredential = Get-Credential

# Define parameters for New-AzVmss
$newAzVmssParams = @{
    ResourceGroupName   = $resourceGroupName
    Location            = $azureRegion
    VMScaleSetName      = $vmssName
    Credential          = $vmCredential
    VirtualNetworkName  = $virtualNetworkName
    SubnetName          = $subnetName
    PublicIpAddressName = $publicIpAddressName
    LoadBalancerName   = $loadBalancerName
    OrchestrationMode  = "Flexible"
}

# Create the virtual machine scale set
New-AzVmss @newAzVmssParams

自動スケーリング設定を作成する

PowerShell を使用して自動スケーリング設定を作成するには、次の手順に従います。

  1. New-AzAutoscaleScaleRuleObjectを使用してルールを作成します。
  2. New-AzAutoscaleProfileObjectを使用してプロファイルを作成します。
  3. New-AzAutoscaleSettingを使用して自動スケール設定を作成します。
  4. Update-AzAutoscaleSettingを使用して設定を更新します。

規則の作成

スケールインルールとスケールアウトルールを作成し、プロファイルに関連付けます。

次のAzure PowerShell例では、New-AzAutoscaleScaleRuleObject コマンドレットを使用します。

Note

次の 2 つのルールが作成されます。

  • CPU 使用率が 70%を超えたときにスケールアウトします。
  • CPU 使用率が 30%未満の場合にスケールインします。
# Define parameters for New-AzAutoscaleScaleRuleObject
$newAzAutoscaleScaleRuleObjectParams = @{
    MetricTriggerMetricName        = "Percentage CPU"
    MetricTriggerMetricResourceUri  = $vmssResourceId
    MetricTriggerTimeGrain          = New-TimeSpan -Minutes 1
    MetricTriggerStatistic         = "Average"
    MetricTriggerTimeWindow         = New-TimeSpan -Minutes 5
    MetricTriggerTimeAggregation    = "Average"
    MetricTriggerOperator          = "GreaterThan"
    MetricTriggerThreshold         = 70
    MetricTriggerDividePerInstance = $false
    ScaleActionDirection           = "Increase"
    ScaleActionType                = "ChangeCount"
    ScaleActionValue               = "1"
    ScaleActionCooldown            = New-TimeSpan -Minutes 5
}
$scaleOutRule = New-AzAutoscaleScaleRuleObject @newAzAutoscaleScaleRuleObjectParams

# Define parameters for New-AzAutoscaleScaleRuleObject
$newAzAutoscaleScaleRuleObjectParams = @{
    MetricTriggerMetricName        = "Percentage CPU"
    MetricTriggerMetricResourceUri  = $vmssResourceId
    MetricTriggerTimeGrain          = New-TimeSpan -Minutes 1
    MetricTriggerStatistic         = "Average"
    MetricTriggerTimeWindow         = New-TimeSpan -Minutes 5
    MetricTriggerTimeAggregation    = "Average"
    MetricTriggerOperator          = "LessThan"
    MetricTriggerThreshold         = 30
    MetricTriggerDividePerInstance = $false
    ScaleActionDirection           = "Decrease"
    ScaleActionType                = "ChangeCount"
    ScaleActionValue               = "1"
    ScaleActionCooldown            = New-TimeSpan -Minutes 5
}
$scaleInRule = New-AzAutoscaleScaleRuleObject @newAzAutoscaleScaleRuleObjectParams

次の表では、New-AzAutoscaleScaleRuleObject コマンドレットで使用されるパラメーターについて説明します。

パラメーター 説明
MetricTriggerMetricName 自動スケーリング トリガー メトリックを設定します
MetricTriggerMetricResourceUri MetricTriggerMetricName メトリックが属するリソースを指定します。 MetricTriggerMetricResourceUri は、スケーリングされるリソースだけでなく、任意のリソースにすることができます。 たとえば、ロード バランサー、データベース、またはスケール セット自体によって作成されたメトリックに基づいて、Virtual Machine Scale Sets をスケーリングできます。 MetricTriggerMetricName は、指定した MetricTriggerMetricResourceUri に存在する必要があります。
MetricTriggerTimeGrain ルールによって監視されるメトリックのサンプリング頻度。 MetricTriggerTimeGrain は、指定されたメトリックの定義済みの値のいずれかであり、12 時間から 1 分の値にする必要があります。 たとえば、MetricTriggerTimeGrain = PT1M"* の場合、メトリックが 1 分ごとにサンプリングされ、MetricTriggerStatistic で指定された集計方法を使用して集計されます。
MetricTriggerTimeAggregation timeGrain の期間内の集計方法。 たとえば、statistic = "Average" で timeGrain = "PT1M" の場合、1 分ごとにメトリックが平均して集計されます。
MetricTriggerStatistic サンプリングされたメトリックの集計に使用する集計方法。 たとえば、TimeAggregation = "Average" の場合、サンプリングされたメトリックが平均して集計されます。
MetricTriggerTimeWindow 自動スケールエンジンがメトリクスを集計するために遡って参照する期間。 この値は、メトリック収集の遅延を上回っている必要があります。これは、リソースによって異なります。 5 分~ 12 時間の範囲で指定する必要があります。 たとえば、10 分間は、自動スケーリングが実行されるたびに、過去 10 分間のメトリックのクエリを実行することを意味します。 この機能により、メトリックが安定し一時的なスパイクへの反応を避けることができます。
MetricTriggerThreshold スケール イベントをトリガーするメトリックの値を定義します。
MetricTriggerOperator メトリック値を評価する際に使用する論理比較演算を指定します。
MetricTriggerDividePerInstance true に設定すると、トリガー メトリックがインスタンスの合計数で除算されます。 たとえば、メッセージ数が 300 で、5 つのインスタンスが実行されている場合、算出されるメトリック値はインスタンスあたり 60 メッセージです。 このプロパティは、すべてのメトリックに適用されるわけではありません。
ScaleActionDirection スケールインまたはスケールアウトを指定します。有効な値は Increase と Decrease です。
ScaleActionType 特定のインスタンス数でスケーリングするか、特定のインスタンス数にスケーリングするか、現在のインスタンス数の割合でスケーリングします。 有効な値には ChangeCount、ExactCount、および PercentChangeCount があります。
ScaleActionCooldown スケール操作の実行後、このルールが別のスケール アクションを開始できるようになるまでに経過する必要がある最小時間。 自動スケーリングでは、各ルールのクールダウンを個別に確認します。 クールダウンにより、メトリックが安定し、 フラッピングを回避できます。

既定の自動スケーリング プロファイルを作成してルールを関連付ける

スケール ルールを定義したら、プロファイルを作成します。 このプロファイルでは、既定、上限、および下限のインスタンス数の制限と、関連付けられているルールを適用できる時間を指定します。

次のAzure PowerShell例では、New-AzAutoscaleProfileObject コマンドレットを使用します。

Note

このプロファイルは既定のプロファイルであるため、スケジュール パラメーターはありません。 既定のプロファイルは、他のプロファイルがアクティブでない場合にアクティブになります。

# Define parameters for New-AzAutoscaleProfileObject
$newAzAutoscaleProfileObjectParams = @{
    Name            = "default"
    CapacityDefault = "1"
    CapacityMaximum = "10"
    CapacityMinimum = "1"
    Rule            = @($scaleOutRule, $scaleInRule)
}
$defaultProfile = New-AzAutoscaleProfileObject @newAzAutoscaleProfileObjectParams

次の表では、New-AzAutoscaleProfileObject コマンドレットで使用されるパラメーターについて説明します。

パラメーター 説明
CapacityDefault メトリックが評価に利用できない場合のインスタンス数。 既定値は、現在のインスタンスの数が既定値より少ない場合にのみ使用されます。
CapacityMaximum リソースのインスタンスの最大数。 インスタンスの最大数は、サブスクリプションで使用できるコア数でさらに制限されます。
CapacityMinimum リソースのインスタンスの最小数。
FixedDateEnd ISO 8601 形式のプロファイルの終了時刻。
FixedDateStart ISO 8601 形式のプロファイルの開始時刻。
Rule このプロファイルがアクティブな場合のスケーリング処理のトリガーとパラメーターを提供するルールのコレクション。 最大 10 個のコンマ区切りのルールを指定できます。
RecurrenceFrequency スケジュールされたプロファイルが有効になる頻度。 この値は week にする必要があります。
ScheduleDay 定期的なスケジュールを指定する際にプロファイルが有効になる日数のコレクション。 日曜日から土曜日までの値を指定できます。 定期的なスケジュールの詳細については、「PowerShell を使用した定期スケジュール」を参照してください。
ScheduleHour プロファイルが有効になる時間 (時) のコレクション。 サポートされている値は、0 から 23 です。
ScheduleMinute プロファイルが有効になる時間 (分) のコレクション。
ScheduleTimeZone プロファイルの時間のタイムゾーン。

自動スケーリング設定を適用する

ルールとプロファイルを定義したら、自動スケール設定を適用してください。 既存の自動スケール設定を更新するには、 Update-AzAutoscaleSettingを使用します。

次のAzure PowerShell例では、New-AzAutoscaleSetting コマンドレットを使用します。

# Define parameters for New-AzAutoscaleSetting
$newAzAutoscaleSettingParams = @{
    Name              = $autoscaleName
    ResourceGroupName = $resourceGroupName
    Location          = $azureRegion
    Profile           = @($defaultProfile)
    Enabled           = $true
    PropertiesName    = $autoscaleName
    TargetResourceUri = $vmssResourceId
}

# Create the autoscale setting
New-AzAutoscaleSetting @newAzAutoscaleSettingParams

自動スケーリング設定に通知を追加する

自動スケール設定に通知を追加して、スケール イベントが発生したときに Webhook をトリガーしたり、電子メール通知を送信したりできるようにします。

次のAzure PowerShell例では、New-AzAutoscaleWebhookNotificationObject コマンドレットを使用します。

# Set variables
$webhookUri = "<WebhookUri>"

# Create the webhook notification
$webhook = New-AzAutoscaleWebhookNotificationObject -Property @{} -ServiceUri $webhookUri

次のAzure PowerShell例では、New-AzAutoscaleNotificationObject コマンドレットを使用して Webhook と電子メール通知を構成します。

Note

Webhook には HTTPS エンドポイントを使用します。

# Set variables
$notificationEmail = "<NotificationEmail>"

# Define parameters for New-AzAutoscaleNotificationObject
$newAzAutoscaleNotificationObjectParams = @{
    EmailCustomEmail                      = @($notificationEmail)
    EmailSendToSubscriptionAdministrator   = $true
    EmailSendToSubscriptionCoAdministrator = $true
    Webhook                               = @($webhook)
}
$notification = New-AzAutoscaleNotificationObject @newAzAutoscaleNotificationObjectParams

次のAzure PowerShell例では、Update-AzAutoscaleSetting コマンドレットを使用して通知を適用します。

# Define parameters for Update-AzAutoscaleSetting
$updateAzAutoscaleSettingParams = @{
    Name              = $autoscaleName
    ResourceGroupName = $resourceGroupName
    Notification      = @($notification)
}

# Update the autoscale notification
Update-AzAutoscaleSetting @updateAzAutoscaleSettingParams

自動スケーリング設定を確認する

次のAzure PowerShell例では、Get-AzAutoscaleSetting コマンドレットを使用して自動スケール設定を取得します。

# Define parameters for Get-AzAutoscaleSetting
$getAzAutoscaleSettingParams = @{
    ResourceGroupName = $resourceGroupName
    Name              = $autoscaleName
}
$autoscaleSetting = Get-AzAutoscaleSetting @getAzAutoscaleSettingParams
$autoscaleSetting | Select-Object -Property *

次のAzure PowerShell例では、Get-AzAutoscaleHistory コマンドレットを使用します。

Note

スケール セットのリソース ID ではなく、自動スケール設定の履歴を照会します。

# Build autoscale setting resource ID
$autoscalePath = "/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName"
$autoscaleProvider = "Microsoft.Insights/autoscaleSettings/$autoscaleName"
$autoscaleResourceId = "$autoscalePath/providers/$autoscaleProvider"

# Retrieve the autoscale history
Get-AzAutoscaleHistory -ResourceId $autoscaleResourceId

スケジュール済みプロファイルと繰り返しプロファイル

Note

Profileを更新するときは、保持するすべてのプロファイルを含めてください。 次の例では、この記事で前に作成した設定にプロファイルを追加します。 他のプロファイルを別の自動スケール設定に適用する場合は、他のプロファイルは保持します。

特別なイベントのスケジュールされたプロファイルを追加する

特定のイベントに対して異なる方法でスケーリングするように自動スケーリング プロファイルを設定します。 たとえば、普段より需要が高まる日には、インスタンスの最大値と最小値の制限を増やしたプロファイルを作成します。

次のAzure PowerShell例では、New-AzAutoscaleProfileObjectコマンドレットとUpdate-AzAutoscaleSettingコマンドレットを使用します。

Note

次の例では、前に定義した既定のプロファイルと同じ規則を使用しますが、特定の日付に対して新しいインスタンス制限を設定します。 新しいプロファイルで使用するさまざまなルールを構成することもできます。 開始値と終了値は、UTC で ISO 8601 タイムスタンプを使用します。

# Set variables
$startTime = "<StartTime>"
$endTime = "<EndTime>"

# Define parameters for New-AzAutoscaleProfileObject
$newAzAutoscaleProfileObjectParams = @{
    Name              = "High-demand-day"
    CapacityDefault   = "7"
    CapacityMaximum   = "30"
    CapacityMinimum   = "5"
    FixedDateEnd      = [datetime]::Parse($endTime)
    FixedDateStart    = [datetime]::Parse($startTime)
    FixedDateTimeZone = "UTC"
    Rule              = @($scaleOutRule, $scaleInRule)
}
$highDemandDay = New-AzAutoscaleProfileObject @newAzAutoscaleProfileObjectParams

# Define parameters for Update-AzAutoscaleSetting
$updateAzAutoscaleSettingParams = @{
    Name              = $autoscaleName
    ResourceGroupName = $resourceGroupName
    Profile           = @($defaultProfile, $highDemandDay)
}

# Update the autoscale profiles
Update-AzAutoscaleSetting @updateAzAutoscaleSettingParams

定期的なスケジュール プロファイルを追加する

定期的なプロファイルでは、毎週繰り返されるスケーリング プロファイルをスケジュールできます。

スケジュールされたプロファイルには開始日と終了日が設定されていますが、定期的なプロファイルには終了時刻がありません。 プロファイルは、次のプロファイルの開始時刻までアクティブなままになります。 したがって、繰り返しプロファイルを作成する場合は、前の繰り返しプロファイルを終了させたい時点で開始する既定の繰り返しプロファイルを作成する必要があります。

次のAzure PowerShell例では、New-AzAutoscaleProfileObjectコマンドレットとUpdate-AzAutoscaleSettingコマンドレットを使用します。

Note

たとえば、週末の金曜日の夜から月曜日の朝にかけて、1 つのインスタンスにスケーリングします。 金曜日の夜に始まり、月曜日の朝に終わる週末プロファイルを構成するには、金曜日の夜に始まるプロファイルを作成し、次に月曜日の朝に始まる既定の設定の定期プロファイルを作成します。

週末プロファイルと、週末プロファイルを終了するための定期的な既定のプロファイルが作成され、前の手順の既定のプロファイルと固定日プロファイルは保持されます。

# Define parameters for New-AzAutoscaleProfileObject
$newAzAutoscaleProfileObjectParams = @{
    Name                = "Weekend"
    CapacityDefault     = "1"
    CapacityMaximum     = "1"
    CapacityMinimum     = "1"
    RecurrenceFrequency = "Week"
    ScheduleDay         = @("Friday")
    ScheduleHour        = @(22)
    ScheduleMinute      = @(0)
    ScheduleTimeZone    = "Pacific Standard Time"
    Rule                = @($scaleOutRule, $scaleInRule)
}
$fridayProfile = New-AzAutoscaleProfileObject @newAzAutoscaleProfileObjectParams

# Define parameters for New-AzAutoscaleProfileObject
$newAzAutoscaleProfileObjectParams = @{
    Name                = "default recurring profile"
    CapacityDefault     = "2"
    CapacityMaximum     = "10"
    CapacityMinimum     = "2"
    RecurrenceFrequency = "Week"
    ScheduleDay         = @("Monday")
    ScheduleHour        = @(0)
    ScheduleMinute      = @(0)
    ScheduleTimeZone    = "Pacific Standard Time"
    Rule                = @($scaleOutRule, $scaleInRule)
}
$defaultRecurringProfile = New-AzAutoscaleProfileObject @newAzAutoscaleProfileObjectParams

# Define parameters for Update-AzAutoscaleSetting
$updateAzAutoscaleSettingParams = @{
    Name              = $autoscaleName
    ResourceGroupName = $resourceGroupName
    Profile           = @(
        $defaultProfile
        $highDemandDay
        $defaultRecurringProfile
        $fridayProfile
    )
}

# Update the autoscale profiles
Update-AzAutoscaleSetting @updateAzAutoscaleSettingParams

スケジュールされたプロファイルの詳細については、「複数のプロファイルでの自動スケール」を参照してください。

その他の自動スケーリング コマンド

自動スケール用の PowerShell コマンドレットの完全な一覧については、 PowerShell モジュール ブラウザーを参照してください。

リソースをクリーンアップする

このチュートリアルで作成したリソースをクリーンアップするには、作成した専用リソース グループを削除します。 次のコマンドレットは、リソース グループとそのすべてのリソースを削除します。

次のAzure PowerShell例では、Remove-AzResourceGroup コマンドレットを使用します。

# Delete the example resource group
Remove-AzResourceGroup -Name $resourceGroupName