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:
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:
Setting up the ‘subscription’ automation variable asset:
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.
Then go through and edit the runbooks, copy and past the following code.
Start VMs:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
workflow StartAzurePlaylistVMs | |
{ | |
$Cred = Get-AutomationPSCredential –Name "PowerShell SvcAcct" | |
Login–AzureRmAccount –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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
workflow StopAzurePlaylistVMs | |
{ | |
$Cred = Get-AutomationPSCredential –Name "PowerShell SvcAcct" | |
Login–AzureRmAccount –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 | |
} | |
} |