PowerShell을 사용하여 Azure SQL Database의 단일 데이터베이스 모니터링 및 크기 조정

적용 대상:Azure SQL Database

이 PowerShell 스크립트 예제에서는 단일 데이터베이스의 성능 메트릭을 모니터링하고, 더 큰 컴퓨팅 크기로 조정하고, 성능 메트릭 중 하나에 대한 경고 규칙을 만듭니다.

Azure를 구독하고 있지 않다면 시작하기 전에 Azure 체험 계정을 만듭니다.

참고

이 문서에서는 Azure와 상호 작용하는 데 권장되는 PowerShell 모듈인 Azure Az PowerShell 모듈을 사용합니다. Az PowerShell 모듈을 시작하려면 Azure PowerShell 설치를 참조하세요. Az PowerShell 모듈로 마이그레이션하는 방법에 대한 자세한 내용은 Azure PowerShell을 AzureRM에서 Azure로 마이그레이션을 참조하세요.

Azure Cloud Shell 사용

Azure는 브라우저를 통해 사용할 수 있는 대화형 셸 환경인 Azure Cloud Shell을 호스트합니다. Cloud Shell에서 Bash 또는 PowerShell을 사용하여 Azure 서비스 작업을 수행할 수 있습니다. 로컬 환경에 아무 것도 설치할 필요 없이 Azure Cloud Shell의 미리 설치된 명령을 사용하여 이 문서의 코드를 실행할 수 있습니다.

Azure Cloud Shell을 시작하려면 다음을 수행합니다.

옵션 예제/링크
코드 블록의 오른쪽 위 모서리에서 사용을 선택합니다. 사용해보기를 선택하면 코드가 Cloud Shell에 자동으로 복사되지 않습니다. Screenshot that shows an example of Try It for Azure Cloud Shell.
https://shell.azure.com으로 이동하거나 Cloud Shell 시작 단추를 선택하여 브라우저에서 Cloud Shell을 엽니다. Screenshot that shows how to launch Cloud Shell in a new window.
Azure Portal의 오른쪽 위에 있는 메뉴 모음에서 Cloud Shell 단추를 선택합니다. Screenshot that shows the Cloud Shell button in the Azure portal

이 문서의 코드를 Azure Cloud Shell에서 실행하려면 다음을 수행합니다.

  1. Cloud Shell을 시작합니다.

  2. 코드 블록의 복사 단추를 선택하여 코드를 복사합니다.

  3. Windows 및 Linux에서 Ctrl+Shift+V를 선택하거나 macOS에서 Cmd+Shift+V를 선택하여 코드를 Cloud Shell 세션에 붙여넣습니다.

  4. Enter를 선택하여 코드를 실행합니다.

PowerShell을 로컬로 설치하고 사용하도록 선택하는 경우 이 자습서에는 Az PowerShell 1.4.0 이상이 필요합니다. 업그레이드해야 하는 경우 Azure PowerShell 모듈 설치를 참조하세요. 또한 PowerShell을 로컬로 실행하는 경우 Connect-AzAccount를 실행하여 Azure와 연결해야 합니다.

샘플 스크립트

# This script requires the following
# - Az.Resources
# - Az.Accounts
# - Az.Monitor
# - Az.Sql

# First, run Connect-AzAccount

# Set the subscription in which to create these objects. This is displayed on objects in the Azure portal.
$SubscriptionId = ''
# Set the resource group name and location for your server
$resourceGroupName = "myResourceGroup-$(Get-Random)"
$location = "westus2"
# Set an admin login and password for your server
$adminSqlLogin = "SqlAdmin"
$password = (New-Guid).Guid # Generates a randomized GUID password. 
# Set server name - the logical server name has to be unique in the system
$serverName = "server-$(Get-Random)"
# The sample database name
$databaseName = "mySampleDatabase"
# The ip address range that you want to allow to access your server via the firewall rule
$startIp = "0.0.0.0"
$endIp = "0.0.0.0"

# Set subscription 
Set-AzContext -SubscriptionId $subscriptionId 

# Create a new resource group
$resourceGroup = New-AzResourceGroup -Name $resourceGroupName -Location $location

# Create a new server with a system wide unique server name
$server = New-AzSqlServer -ResourceGroupName $resourceGroupName `
    -ServerName $serverName `
    -Location $location `
    -SqlAdministratorCredentials $(New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $adminSqlLogin, $(ConvertTo-SecureString -String $password -AsPlainText -Force))

# Create a server firewall rule that allows access from the specified IP range
$serverFirewallRule = New-AzSqlServerFirewallRule -ResourceGroupName $resourceGroupName `
    -ServerName $serverName `
    -FirewallRuleName "AllowedIPs" -StartIpAddress $startIp -EndIpAddress $endIp

# Create a blank database with an S0 performance level
$database = New-AzSqlDatabase  -ResourceGroupName $resourceGroupName `
    -ServerName $serverName `
    -DatabaseName $databaseName `
    -RequestedServiceObjectiveName "S0" `
    -SampleName "AdventureWorksLT"

# Monitor the DTU consumption on the database in 5 minute intervals
$MonitorParameters = @{
  ResourceId = "/subscriptions/$($(Get-AzContext).Subscription.Id)/resourceGroups/$resourceGroupName/providers/Microsoft.Sql/servers/$serverName/databases/$databaseName"
  TimeGrain = [TimeSpan]::Parse("00:05:00")
  MetricNames = "dtu_consumption_percent"
}
$metric = Get-AzMetric @monitorparameters
$metric.Data

# Scale the database performance to Standard S1
$database = Set-AzSqlDatabase -ResourceGroupName $resourceGroupName `
    -ServerName $servername `
    -DatabaseName $databasename `
    -Edition "Standard" `
    -RequestedServiceObjectiveName "S1"


# Set up an Alert rule using Azure Monitor for the database
# Add an Alert that fires when the pool utilization reaches 90%
# Objects needed: An Action Group Receiver (in this case, an email group), an Action Group, Alert Criteria, and finally an Alert Rule.

# Creates an new action group receiver object with a target email address.
$receiver = New-AzActionGroupReceiver `
    -Name "my Sample Azure Admins" `
    -EmailAddress "azure-admins-group@contoso.com"

# Creates a new or updates an existing action group.
$actionGroup = Set-AzActionGroup `
    -Name "mysample-email-the-azure-admins" `
    -ShortName "AzAdminsGrp" `
    -ResourceGroupName $resourceGroupName `
    -Receiver $receiver

# Fetch the created AzActionGroup into an object of type Microsoft.Azure.Management.Monitor.Models.ActivityLogAlertActionGroup
$actionGroupObject = New-AzActionGroup -ActionGroupId $actionGroup.Id

# Create a criteria for the Alert to monitor.
$criteria = New-AzMetricAlertRuleV2Criteria `
    -MetricName "dtu_consumption_percent" `
    -TimeAggregation Average `
    -Operator GreaterThan `
    -Threshold 90

# Create the Alert rule.
# Add-AzMetricAlertRuleV2 adds or updates a V2 (non-classic) metric-based alert rule.
Add-AzMetricAlertRuleV2 -Name "mySample_Alert_DTU_consumption_pct" `
        -ResourceGroupName $resourceGroupName `
        -WindowSize (New-TimeSpan -Minutes 1) `
        -Frequency (New-TimeSpan -Minutes 1) `
        -TargetResourceId "/subscriptions/$($(Get-AzContext).Subscription.Id)/resourceGroups/$resourceGroupName/providers/Microsoft.Sql/servers/$serverName/databases/$databaseName" `
        -Condition $criteria `
        -ActionGroup $actionGroupObject `
        -Severity 3 #Informational

<#
# Set up an alert rule using Azure Monitor for the database
# Note that Add-AzMetricAlertRule is deprecated. Use Add-AzMetricAlertRuleV2 instead.
Add-AzMetricAlertRule -ResourceGroup $resourceGroupName `
    -Name "MySampleAlertRule" `
    -Location $location `
    -TargetResourceId "/subscriptions/$($(Get-AzContext).Subscription.Id)/resourceGroups/$resourceGroupName/providers/Microsoft.Sql/servers/$serverName/databases/$databaseName" `
    -MetricName "dtu_consumption_percent" `
    -Operator "GreaterThan" `
    -Threshold 90 `
    -WindowSize $([TimeSpan]::Parse("00:05:00")) `
    -TimeAggregationOperator "Average" `
    -Action $(New-AzAlertRuleEmail -SendToServiceOwner)
#>

# Clean up deployment 
# Remove-AzResourceGroup -ResourceGroupName $resourceGroupName

참고 항목

모든 메트릭 목록은 지원되는 메트릭을 참조하세요.

Get-AzSqlDatabaseActivity를 사용하여 데이터베이스 작업의 상태를 가져오고 Stop-AzSqlDatabaseActivity를 사용하여 데이터베이스 업데이트 작업을 취소합니다.

배포 정리

다음 명령을 사용하여 리소스 그룹 및 모든 관련 리소스를 제거합니다.

Remove-AzResourceGroup -ResourceGroupName $resourcegroupname

스크립트 설명

이 스크립트는 다음 명령을 사용합니다. 표에 있는 각 명령은 명령에 해당하는 문서에 연결됩니다.

명령 메모
New-AzResourceGroup 모든 리소스가 저장되는 리소스 그룹을 만듭니다.
New-AzSqlServer 단일 데이터베이스 또는 Elastic Pool을 호스트하는 서버를 만듭니다.
Get-AzMetric 데이터베이스의 크기 사용량 정보가 표시됩니다.
Set-AzSqlDatabase 데이터베이스 속성을 업데이트하거나 데이터베이스를 Elastic Pool 안팎으로 이동합니다.
Add-AzMetricAlertRule (사용되지 않음) 나중에 메트릭을 자동으로 모니터링하도록 경고 규칙을 추가하거나 업데이트합니다. 클래식 메트릭 기반 경고 규칙에만 적용됩니다.
Add-AzMetricAlertRuleV2 나중에 메트릭을 자동으로 모니터링하도록 경고 규칙을 추가하거나 업데이트합니다. 클래식이 아닌 메트릭 기반 경고 규칙에만 적용됩니다.
Remove-AzResourceGroup 모든 중첩 리소스를 포함한 리소스 그룹을 삭제합니다.

다음 단계

Azure PowerShell에 대한 자세한 내용은 Azure PowerShell 설명서를 참조하세요.

추가 PowerShell 스크립트 샘플은 Azure PowerShell 스크립트에 있습니다.