Automate Azure SQL Size using Azure Automation (Manual)

Recently a customer asked me how to save cost on their Azure SQL database without moving away from DTU based subscription model. In this case this customer knows exactly at what time their database is heavily utilized, and when it’s idling. So with a script its easy to automate.

In this manual we are going to size a SQL database from S4 to S3.

Step 1: In this first step we are going to add some modules to your Automation Account. Go to modules, and click on Browse gallery

From the Gallery search for az.accounts, click on it

Next make sure to Import the module

Now browse the Gallery again, this time search for az.sql and make sure to import this module as well.

STEP 2: Now we will need to add some variables to your automation account. These variables will need to be filled with information about your Azure SQL Database and Server. Create the following variables, and make sure that you fill them.

  • Resourcegroup
  • Servername (without database.windows.net)
  • Database
  • ScaleDownTier
  • ScaleUpTier

STEP 3: Now go to runbooks, and create a new runbook!

Give your runbook a name, as type select PowerShell!

In the new opened window copy and paste the code from below. Adjust the variables $Edition and $PricingTier to your needs.

$ResourceGroupName = Get-AutomationVariable -Name "Resourcegroup"
 $ServerName = Get-AutomationVariable -Name "Servername"
 $DatabaseName = Get-AutomationVariable -Name "Database"
 $Edition = "Standard"
 $PricingTier = Get-AutomationVariable -Name "ScaleDownTier"

 
# Keep track of time
$StartDate=(GET-DATE)

# Connect to azure
$context = (Connect-AzAccount -Identity).Context
$Tenant = Get-AzTenant
$Subscription  = Get-AzSubscription -TenantID $Tenant.TenantId
 
 
 

# Log in to Azure with AZ (standard code)

Write-Verbose -Message 'Connecting to Azure'
  
# Name of the Azure Run As connection
$ConnectionName = 'AzureRunAsConnection'
try
{
    # Get the connection properties
    $ServicePrincipalConnection = Get-AutomationConnection -Name $ConnectionName      
   
    'Log in to Azure...'
    $null = Connect-AzAccount `
        -ServicePrincipal `
        -TenantId $ServicePrincipalConnection.TenantId `
        -ApplicationId $ServicePrincipalConnection.ApplicationId `
        -CertificateThumbprint $ServicePrincipalConnection.CertificateThumbprint 
}
catch 
{
    if (!$ServicePrincipalConnection)
    {
        # You forgot to turn on 'Create Azure Run As account' 
        $ErrorMessage = "Connection $ConnectionName not found."
        throw $ErrorMessage
    }
    else
    {
        # Something else went wrong
        Write-Error -Message $_.Exception.Message
        throw $_.Exception
    }
}

  

# Getting the database for testing and logging purposes

$MyAzureSqlDatabase = Get-AzSqlDatabase -ResourceGroupName $ResourceGroupName -ServerName $ServerName -DatabaseName $DatabaseName
if (!$MyAzureSqlDatabase)
{
    Write-Error "$($ServerName)\$($DatabaseName) not found in $($ResourceGroupName)"
    return
}
else
{
    Write-Output "Current pricing tier of $($ServerName)\$($DatabaseName): $($MyAzureSqlDatabase.Edition) - $($MyAzureSqlDatabase.CurrentServiceObjectiveName)"
}


# Set Pricing Tier Database

# Check for incompatible actions
if ($MyAzureSqlDatabase.Edition -eq $Edition -And $MyAzureSqlDatabase.CurrentServiceObjectiveName -eq $PricingTier)
{
    Write-Error "Cannot change pricing tier of $($ServerName)\$($DatabaseName) because the new pricing tier is equal to current pricing tier"
    return
}
else
{
    Write-Output "Changing pricing tier to $($Edition) - $($PricingTier)"
    $null = Set-AzSqlDatabase -DatabaseName $DatabaseName -ServerName $ServerName -ResourceGroupName $ResourceGroupName -Edition $Edition -RequestedServiceObjectiveName $PricingTier
}
 




# Show when finished

$Duration = NEW-TIMESPAN –Start $StartDate –End (GET-DATE)
Write-Output "Done in $([int]$Duration.TotalMinutes) minute(s) and $([int]$Duration.Seconds) second(s)"
 

Use the menu to Save your runbook, use the Test pane to review the output of your PowerShell script. When ready Publish your runbook!

STEP 4: Last step is to create a schedule. From your workbook go to Schedules, and Add an schedule.

Create a new schedule based on your requirements/needs.

Click create to finalize the process. Now go back to your SQL database. When the change is happening, you should see a update line like below that shows that the pricing tier is being updated!

Add a Comment

Your email address will not be published. Required fields are marked *