Microsoft Azure Automation

Microsoft recently added a very useful feature to automate things in Azure. It is in preview at the time of writing, but I decided to try it for starting and stopping our virtual machines used for testing, and it works really well. Here is a link to a step-to-step guide: http://blogs.technet.com/b/keithmayer/archive/2014/04/06/step-by-step-getting-started-with-windows-azure-automation.aspx

Here is my “workflow” for starting:

workflow Start-nnn
{
    # Specify Azure Subscription Name
    $subName = 'nnn'
    # Connect to Azure Subscription
    Connect-Azure -AzureConnectionName $subName
    Select-AzureSubscription -SubscriptionName $subName

    # Start VMs
    $vmList = ('vm1','vm2')
    For ( $vmCount = 0; $vmCount -lt $vmList.Count; $vmCount++) {
        Write-Output ("Getting virtual machine status for {0}..." -f $vmList[$vmCount])
        $vm = Get-AzureVM -ServiceName $vmList[$vmCount] -Name $vmList[$vmCount]
        if ( $vm.InstanceStatus -eq 'StoppedDeallocated' ) {
            Write-Output ("Starting {0}..." -f $vm.Name)
            Start-AzureVM -ServiceName $vm.ServiceName -Name $vm.Name
        }
    }
}

And for stopping:

workflow Stop-nnn
{
    # Specify Azure Subscription Name
    $subName = 'nnn'
    # Connect to Azure Subscription
    Connect-Azure -AzureConnectionName $subName
    Select-AzureSubscription -SubscriptionName $subName

    # Shutdown VMs
    $vmList = ('vm1','vm2')
    For ( $vmCount = 0; $vmCount -lt $vmList.Count; $vmCount++) {
        Write-Output ("Getting status for {0}..." -f $vmList[$vmCount])
        $vm = Get-AzureVM -ServiceName $vmList[$vmCount] -Name $vmList[$vmCount]
        if ( $vm.InstanceStatus -eq 'ReadyRole' ) {
            Write-Output ("Stopping {0}..." -f $vm.Name)
            Stop-AzureVM -ServiceName $vm.ServiceName -Name $vm.Name -Force
        }
    }
}
Advertisements

Leave a Reply

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

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 )

Google+ photo

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

Connecting to %s