Tinus vd H Tinus vd H

Automatically Scale Azure App Service Plan on a Schedule

I recently started making use of my monthly allocation of Azure credits by hosting a WordPress site for a private function on Azure App Services.

At the time of writing, my monthly Azure credits were R910 per month. I wanted my website (and accompanying PWA) to be pretty performant and knew that there would be days that my website would stop functioning if I used one of the Azure shared infrastructure pricing tiers for my app (F1/D1) – as these limit the amount of computing power available to you per day.

If there is one thing you learn as a South African, it’s how to make your money go further as our politicians try and devalue the currency.

Since I started working on Azure back in 2016, PowerShell has been my favourite tool for getting the job done. My plan of attack was simple.. utilise the AzureRM PowerShell module on my local desktop to execute a script to set the App Service Plan to B1 during the day and switch it down to D1 during the evening and early morning hours. As all experienced developers do, I headed over to the Microsoft documentation for AzureRM. Very quickly I realised that Azure’s security improvements were going to make the task way more difficult than it needed to be. So, I found a shortcut….or I remembered that there was an easier way. I’ve summarised the approach for you below.

Make use of an Azure Automation account and its built-in PowerShell Runbook.

Create a new Azure Automation Account by going to Resources -> Add and then searching for Automation.

Proceed to creating the Automation Account by providing it with a name, selecting your subscription and making sure to select the same resource group as the one containing the App Service Plan you want to manipulate. Also, ensure to select “Yes” for “Create Azure Run As account”. This account is essentially an Azure ServicePrinciple – which for now, you can think of as an account with direct access connections to execute Azure Powershell commands on your resources without requiring additional authentication.

Proceed to creating the Automation Account by providing it with a name, selecting your subscription and making sure to select the same resource group as the one containing the App Service Plan you want to manipulate. Also, ensure to select “Yes” for “Create Azure Run As account”. This account is essentially an Azure ServicePrinciple – which, for now, you can think of as an account with direct access connections to execute Azure PowerShell commands on your resources without requiring additional authentication.

After clicking create, Azure will do it’s thing and notify you once the Automation Account has been created. Go ahead and check it out. Once you’ve had a look around, click on “Runbooks” in the “Process Automation” section of the side menu. Azure takes the liberty of creating you 3 test Runbooks, one a Graphical Runbook, one a Python Runbook and a PowerShell runbook. For now, create a new runbook and call it something useful like “ScaleUpAppServicePlanScript” and make sure to specify the runbook as a PowerShell type runbook. Once done, go back to your list of runbooks and copy the contents of the tutorial PowerShell runbook into your own runbook. If your too lazy to navigate back, the code is below to copy. You only need the first try-catch block and you can ignore the rest.

$connectionName = "AzureRunAsConnection"
try
{
    # Get the connection "AzureRunAsConnection "
    $servicePrincipalConnection=Get-AutomationConnection -Name $connectionName         

    "Logging in to Azure..."
    Add-AzureRmAccount `
        -ServicePrincipal `
        -TenantId $servicePrincipalConnection.TenantId `
        -ApplicationId $servicePrincipalConnection.ApplicationId `
        -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint 
}
catch {
    if (!$servicePrincipalConnection)
    {
        $ErrorMessage = "Connection $connectionName not found."
        throw $ErrorMessage
    } else{
        Write-Error -Message $_.Exception
        throw $_.Exception
    }
}

This script already works, however, you will likely get an error along the lines of the below when you try to run it. We first need to install a few PowerShell modules.

The term 'Find-AzureRmResource' is not recognized as the name of a cmdlet...

Save the runbook and head back to your Automation account and select “Modules gallery” under “Shared Resources” in the side menu. Search and import the following modules one by one in the same order as I have specified.

  1. AzureRM
  2. AzureRM.profile
  3. AzureRM.Websites

Once all modules head back to your Powershell RunBook and replace your code with the following. Please make sure to change to change your ResourceGroup and App ServicePlan names where specified in the code. Also, specify the Tier Name you want for the UpScale. In my example B1 will be the UpScaled tier and D1 will be the DownScaled tier.

Write-Output "Scale Up App Service Plan" 
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force

$connectionName = "AzureRunAsConnection"

try {
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName 
 Add-AzureRmAccount `
        -ServicePrincipal `
        -TenantId $servicePrincipalConnection.TenantId `
        -ApplicationId $servicePrincipalConnection.ApplicationId `
        -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint 

Set-AzureRmAppServicePlan -ResourceGroupName "YourAppResourceGroupNameHere" -Name "YourAppServicePlanNameHere"  -Tier B1 
}catch {


if (!$servicePrincipalConnection){
$ErrorMessage = "Connection $connectionName not found."
throw $ErrorMessage } else{ 
Write-Error -Message $_.Exception 
throw $_.Exception
}}

You can test the above by changing your App Service Plan to any tier (other than B1) manually and then running a test of the script. The script should complete successfully and if you go visit your App Service Plan, it should now be on B1. Tada! Next, we will create a schedule to automatically run this script for us. Go ahead and publish this ScaleUp Runbook. Now, in the Runbook Section, click on schedules and click on “Add a schedule”. Create a schedule with a descriptive name and set the time for the script to run. Also make sure to set the “Recurrence” setting to “Recurring”.

Congratulations, you now have an automated script that will scale up your App Service Plan at the times specified. Repeat the above steps for a new Runbook called something like “ScaleDownMyAppServicePlan”, copy the same code and just replace the -Tier with the lower tier and set up a schedule for when this script should trigger.

Share Post :

More Posts