Schedule scaling of your Azure resources

This blog post shows how you can use Azure Functions and PowerShell to schedule scaling of Azure resources. Something that can save you quite a few bucks if you for example scale down test environments during nights and weekends, when they’re not used anyway.

I use Azure environments for a lot of things. I’m doing proof-of-concepts, demoing,  or testing a new version of something. I also use it for several development and test environments,  continuous deployment and running automated tests. I want my environments to be as fast as possible, of course, but I also want to keep the costs down. I often use PowerShell to administrate my Azure resources, and I knew that you can run PowerShell in an Azure Function. So, I wanted to see how much work it was to automatically scale down a Web App and an SQL database during nights and weekends.

I started by creating a new Function App. It’s pretty straight forward, only thing to consider is what hosting plan to use. You can read up on the two alternatives here. I’m pretty sure the cost will be close to zero for this App, whatever you select.

I added a PowerShell timer triggered function, named it “ScaleDownDevEnvironment” and set the schedule with that quite non-intuitive CRON expression. I set the schedule to “0 0 19 * * MON-FRI”, which means that it will run at UTC 19:00 every Monday to Friday.

Now I got a PowerShell script that will run on my schedule. I added a few commands that will login to Azure and scale down a Web App and an SQL database. My “run.ps1” looks like this:

That’s it! Five lines of code, and my development environment is now automatically scaled down at 19:00 every weekday. All I need to do now is to create another timer triggered function that will scale the environment up every morning.
I moved the commands that login to Azure to another file, so that I can re-use it in my “scale up”-function. At the same time I changed from using my own Azure login to using a Service Principal. Take a look here on how to do that.
I added a new file and created a PowerShell function called Login:

The new function is imported to the original file like this:

Import-Module "D:\home\site\wwwroot\ScaleDownDevEnvironments\LoginToAzure.ps1"

The path to the file is always “D:.…\<Your Azure Function name>\<Your file name>

My run.ps1 now looks like this:

As you can see I topped it off by sending a notification to a Slack channel.  Here’s the NotifySlack function:

Happy automation! 🙂

 

Leave a Reply