Stop and Start VMs with Automation on Microsoft Azure

Introduction

Today we'll talk about Automation, a solution inside Microsoft Azure that can be used to save time and reduce costs.

In Automation, Windows PowerShell runbooks helps you work smarter to control the creation, deployment, monitoring and maintenance of the Azure features and third-party applications. Azure AD makes our life simpler by integrating with Automation which we can use to create the service user account that will be used authenticate and run Automation jobs, facilitating and optimizing management of the environment in everyday life.

In this article, we will see how to create an Automation account and to deploy a script to switch on and off VMs.

Creating the service user

To create the user, navigate to Active Directory in Azure, then select Users Tab and finally Add Users at the bottom**.
**

During the creation wizard, we have three options for creating the user: New user in your organization, Microsoft Account or Existing User in another AD Directory.** **

In this article, I will Create a new user for my organization. Type a name for the user, and then click Next.

Then put the Name and Display Name and click Next

Click Create

Then go to the user's account and change the password. Now let's add the user as a Co-Admin in your signature of Microsoft Azure.

Go to Settings >  Administrators> Add
**
**

At this moment, your user is ready for use.

Creating an automation account

**
**

Navigate to Automation >> Create

Then give it a Name for the Account and choose your Region, then click Create

Your Automation account is created.

Add user to run the Runbook

Select your Automation account, then go to Assets>Add Settings

**
**

**
**

Select the option Add Credential

**
**

Now select the type of credential that the user will use, let's choose Windows PowerShell Credential. Add the user then click Next

**
**

Then add the username and password and click Finish

**
**

Verify that the user was added successfully.

Script Models

Here are the two scripts we used in this article. Remember this is a very simple example to automate your environment. Feel free to improve the scripts below.

Start-AzureVM

workflow Start-AzureVM
{   
    #Configuração do Script para Ligar a VM, criado por Michel Jatobá.
    
    $AutomationCredential = "userautomation@dominio.com.br" # Credencial que vai ser utilizada para executar o Script.
    $AzureSubscription = "Subscrption Demo" #Selecione o nome da Subscription
    $ServiceNamesToIgnore = @("Server-01","Server-02") # Adicione os "ServiceName" de cada Servidor que vai ser ligado.
    $HostNamesToIgnore = @("Server01-01","Server-02") # Adicione os "HostName" de cada Servidor que vai ser ligado.
    
    $Cred = Get-AutomationPSCredential -Name $AutomationCredential
    $output = Add-AzureAccount -Credential $Cred 
    Select-AzureSubscription -SubscriptionName $AzureSubscription
 
    Write-Output "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
    
    Write-Output "Iniciando Serviço"
    
    Write-Output "Iniciando as VMs!!!"
 
    Get-AzureVM | ? -Filterscript { $_.Status -eq 'StoppedDeallocated' `
                        -and $ServiceNamesToIgnore -notcontains $_.ServiceName `
                        -and $HostNamesToIgnore -notcontains $_.Name } |
           ForEach-Object {
                Write-Output "Ligando as VMs : $($_.Name), ServiceName $($_.ServiceName)"
                $null = Start-AzureVM -Name $_.Name -ServiceName $_.ServiceName 
            }
     
     Write-Output "Ligamento Completo da VMs "
    
    Write-Output "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
 
}

*Stop-AzureVM
*

workflow Stop-AzureVM
{   
    #Configuração do Script para Desligar a VM, criado por Michel Jatobá.
    
    $AutomationCredential = "userautomation@dominio.com.br" # Credencial que vai ser utilizada para executar o Script.
    $AzureSubscription = "Subscription Demo" #Selecione o nome da Subscription
    $ServiceNamesToIgnore = @("Server-01","Server-02") # Adicione os "ServiceName" de cada Servidor que não vai ser desligado.
    $HostNamesToIgnore = @("Server-01","Server-02") # Adicione os "HostName" de cada Servidor que não vai ser desligado.
    
    $Cred = Get-AutomationPSCredential -Name $AutomationCredential
    $output = Add-AzureAccount -Credential $Cred 
    Select-AzureSubscription -SubscriptionName $AzureSubscription
 
    Write-Output "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
    
    Write-Output "Iniciando Serviço"
    
    Write-Output "Iniciando desligamento das VMs!!!"
 
    Get-AzureVM | ? -Filterscript { $_.Status -eq 'ReadyRole' `
                        -and $ServiceNamesToIgnore -notcontains $_.ServiceName `
                        -and $HostNamesToIgnore -notcontains $_.Name } |
           ForEach-Object {
                Write-Output "Desligando a VM : $($_.Name), ServiceName $($_.ServiceName)"
                $null = Stop-AzureVM -Name $_.Name -ServiceName $_.ServiceName -Force 
            }
     
     Write-Output "Desligamento Completo da VMs "
    
    Write-Output "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
 
}

Creating a Runbook

Now let's create the Runbook to switch servers and schedule timetables to do it automatically. 

*To create the *Runbook go to Runbooks >Quick Create 

1- We will create the Runbook with the name Start-AzureVM (Stop-AzureVM);
2- Select a storage, we calling it DemoAutomation;
3- Choose your Subscription;

Then click Create

Check the Runbooks created

In Runbooks click **Start-AzureVm **

**
**

Inside the Runbook go to Author option and add the Script below:

For this demo,  I've created three servers with the names Automation-01, Automation-02 and Automation-03, to demonstrate how it works.

In the above Script I made an exception to ignore two of the three servers, working only with the Automation-02.

Now let's Test it first and then we can Publish

**
**

When you click Test, the Runbook will check and run the Script  

Now let's see if only Automation-02 is still running.

Creating tasks to the Runbook

Now we will create a scheduled job to do it automatically every day, go to** Schedule**, and then click LinkTo a New Schedule

Type a Name to the task and click Next

Now let's choose Daily to call every day from 8:00 in the morning

Now our task is created. Every day this task will start the machine at 8:00 in the morning. Proceed to create another task for night jobs as well for the Stop-AzureVM runbook.

Credits:

This document was originally published as  http://www.micheljatoba.com.br/2015/09/desligando-e-ligando-vms-no-microsoft.html and has been reproduced here to allow the community to correct any inaccuracies or provide other improvements until you update the original version of this topic.