Save VM Run Costs in Azure – Shut em down!

One of the benefits of public cloud services is the rich set of APIs they make available to developers and IT Pros alike.

Traditionally if you requested compute resources for development or testing purposes you placed a request, waited for your resources to be provisioned and then effectively left them running.

Periodic audits by your IT Ops team might have picked up development or test machines that were no longer required, but these audits might occur only once your businesses infrastructure started to run low on free resources.

As a demonstration of how easy it is to manage resources in Azure take a look at the PowerShell script below.  In less than 30 lines of code I can enumerate all virtual machines in a subscription and then power them off.  I could just as easily do this to power them on (granted there may be a required order to power-on).

# Based on the August 2014 PowerShell Cmdlets (v2.4 of Azure SDK)
Import-Module "C:\Program Files (x86)\Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1"
Function ForceShutdownVM($virtualMachine)
Write-Host "Looking at host" $_.Name ForegroundColor Yellow
if($_.Status -ne "StoppedDeallocated")
if($_.InstanceName -Like "*_IN_*")
Write-Host "`tThis is a Cloud Service and requires deletion to save run costs." ForegroundColor Red
Write-Host "`tForcing Shutdown of VM" ForegroundColor Red
Stop-AzureVM Name $_.Name Force
Write-Host "`tVM is already off" ForegroundColor Green
# Assumes you have previously downloaded the subscription details
# using the Get-AzurePublishSettingsFile Cmdlet
Select-AzureSubscription SubscriptionName $Args[0]
Get-AzureVM | ForEach-Object {ForceShutdownVM($_)}

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s