Sequentially Start & Stop Azure VMs – Azure Automation

Following on from my previous blog post, this is how I managed to sequentially start and stop Azure VMs (Virtual Machines) by using Azure Automation.

First thing you need to do is setup an Azure Automation account – good news if you’re a light user, this is free!

You will need to create some assets:

2016-07-25_1052

The two assets you need to create are credentials and a subscription automation variable.

The credentials the most important part to this for obvious reasons and just like in my previous post, you can’t use a Microsoft account here, you need to create for yourself an organisational based account in Azure setup as a co-administrator (Azure ASM) or contributer (Azure ARM).

Setting up the credential asset:

2016-07-25_1056

Setting up the ‘subscription’ automation variable asset:

2016-07-25_1054

Next thing to do is setup a new runbook, make sure you choose ‘PowerShell Workflow‘.

Do this step twice, one runbook to Start VMs and another runbook to Stop VMs.

2016-07-25_1038

Then go through and edit the runbooks, copy and past the following code.

Start VMs:


workflow StartAzurePlaylistVMs
{
$Cred = Get-AutomationPSCredential Name "PowerShell SvcAcct"
LoginAzureRmAccount Credential $Cred
$subscription = Get-AutomationVariable Name "subscription"
Select-AzureRmSubscription SubscriptionName $subscription
$VMs = Get-AzureRmVM | where {$_.Name -match 'playlist'}
ForEach Parallel ($VM in $VMs)
{
Start-AzureRmVM Name $VM.Name ResourceGroupName $VM.ResourceGroupName
}
}

Stop VMs:


workflow StopAzurePlaylistVMs
{
$Cred = Get-AutomationPSCredential Name "PowerShell SvcAcct"
LoginAzureRmAccount Credential $Cred
$subscription = Get-AutomationVariable Name "subscription"
Select-AzureRmSubscription SubscriptionName $subscription
$VMs = Get-AzureRmVM | where {$_.Name -match 'playlist'}
ForEach Parallel ($VM in $VMs)
{
Stop-AzureRmVM Name $VM.Name ResourceGroupName $VM.ResourceGroupName Force
}
}

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com 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