Save VM Run Costs in Azure - Shut em down!
- Published on
- Reading time
- Authors
- Name
- Simon Waight
- Mastodon
- @simonwaight
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
}
else
{
Write-Host "`tForcing Shutdown of VM" -ForegroundColor Red
Stop-AzureVM -Name $_.Name -Force
}
}
else
{
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($_)}
Grab it from this Gist also: https://gist.github.com/sjwaight/69db4ed51a2be401e8fd