Search code examples
wcfvisual-studio-2015azure-web-rolesazure-virtual-machineazure-cloud-services

How to limit WebRole instance size in Azure?


How I might put a check into the build to make sure an invalid VM size is not accidentally uploaded?

Background: I recently became aware of just how easy it is to inadvertently configure an Azure WebRole instance VM size to an 'expensive' option on Azure.

At the risk of appearing very stupid, and for those who are interested, this is how I did it... I was exploring the settings of my WebRole in Visual Studio, and I must have changed the default single 'ExtraSmall' (AO) VM size to multiple 'ExtraLarge' (A4) which when next deployed, resulted in my usage jumping to many dollars a day, and running out of Azure credit quite quickly ... Doh!!

It got me thinking about how I might put a check into the build to make sure an invalid VM size is not accidentally uploaded?


Solution

  • After considering various powershell, and azure api approaches, I decided the quickest and easiest way was to add a pre-build event on the Cloud Service project (the one that has the .csdef file) as follows...

    for /F "tokens=5 delims=<>= " %%n in ('findstr "vmsize=" $(ProjectDir)ServiceDefinition.csdef') do (if "ExtraSmall"==%%n (exit 0) else (exit 1))
    

    That's it!

    For those who want to know how it works... this pre-build event is a command line/batch file command that can be placed directly in the pre-build events of the project, on a single line. It opens the ServiceDefinition.csdef file and finds the line that contains the text 'vmsize='. This returns the following line...

    <WebRole name="WCFServiceWebRole1" vmsize="ExtraSmall">
    

    Then, using the following characters as delimiters (<,>,=,{space}), it takes the 5th token from that line, which in this case gives us...

    "ExtraSmall"
    

    ...It then compares that value against the literal string "ExtraSmall", and returns errorlevel 0 if it matches, or errorlevel 1 if not. returning errorlevel 1 fails the build and stops any subsequent package and deployment from resulting in the wrong VM size from being deployed in Azure.