Manage Azure VM Schedules: Control Costs & Efficiency

Published:3 September 2020 - 9 min. read

Azure Cloud Labs: these FREE, on‑demand Azure Cloud Labs will get you into a real‑world environment and account, walking you through step‑by‑step how to best protect, secure, and recover Azure data.

Cost. That’s one of the things to watch out for when managing Azure resources. When you generate your Azure usage report, Azure virtual machine usage would probably be the biggest cost contributor. It may be beneficial to create an Azure VM schedule.

Not a reader? Watch this related video tutorial!
Not seeing the video? Make sure your ad blocker is disabled.

You should assess whether your VMs need to be up and running always or if some VMs can be stopped at a specific schedule to save operational costs.

Stopping Azure VMs by schedule is already a built-in feature. This feature allows you to set a schedule to gracefully shutdown the Azure VMs to deallocate them. But how do you start those Azure VMs programmatically at a schedule?

To create an Azure VM scheduled start time, you can utilize Tags and Azure Automation. In this article, you will learn how to use Tags and create a PowerShell Runbook to schedule the startup of Azure virtual machines.

Requirements

If you plan to do more than just read this article and would want to try out the examples, you need to meet these requirements.

Planning Ahead

As with any project, there are things that you need to plan out for. You will need to define your operating variables, such as the virtual machine name(s), resource group, automation account, and tags.

In this article, the following will be used. It is recommended for you to plan a similar list for your environment.

  • Resource Group Name: ATA
  • Virtual Machine Names: AzVM1, AzVM2
  • Automation Account Name: PS-Demo-AA
  • Automation RunBook Name: Azure-VM-Schedule-Start-6am
  • Tags: StartTime=”6am”
  • Startup schedule: 06:00:00

Assigning the Azure VM Schedule Tag

In ensuring that those with Azure VM schedule will start as part of the automation runbook, the virtual machines must be tagged. Follow the process below to add tags to your target Azure VMs.

In the next sections, you learn how to assign the Azure VM schedule tag using the Azure Portal and PowerShell.

Assigning the Azure VM Schedule Tag (Azure Portal)

Using the Azure Portal to assign tags to multiple virtual machines is quick and easy. First, log in to the Azure Portal. Then, go to Virtual Machines and select the virtual machines that will be tagged. In the example below, AzVM1 and AzVM2 are chosen. After making your selection, click on the Assign tags button.

Azure Virtual Machines are selected for assigning tags
Azure Virtual Machines are selected for assigning tags

Then, as the Assign tags fly-out appears, enter this new tag’s Name and Value as StartTime:6am. Then click on Save.

Assign tags to Azure VMs
Assign tags to Azure VMs

Assigning the Azure VM Schedule Tag (Azure PowerShell)

Using the Azure Portal may be easy and convenient, but if hundreds of VMs need to be tagged, you’re far better off using PowerShell.

If you prefer to add tags to your Azure VMs using PowerShell, you can use the code below. Make sure to change the values of the -Name and -ResourceGroupName parameters to reflect the name of your virtual machine and resource group.

## Get the Virtual Machine properties
$azVM = Get-AzVM -Name AzVM1 -ResourceGroupName ATA

## Get the existing tags
$tags = $azVM.Tags

## Add a new tag
$tags += @{StartTime="6am"}

## Apply the new tag collection to the Virtual Machine
Set-AzResource -Name $azVM.Name -ResourceGroupName $azVM.ResourceGroupName  -ResourceType $azVM.Type -Tags $tags

After running the code above in Azure PowerShell, you would see a similar output as the image shown below.

Adding tags to the Azure virtual machine
Adding tags to the Azure virtual machine

If you need to create the Azure VM schedule tag on other virtual machines, repeat the same steps above but change the name of the target virtual machine. Or, if you want to take things further, you can enhance the script to accept multiple VMs for input so that they are tagged all at once.

Creating the Azure Automation Runbook

There are two ways to create a runbook. The first way is to create the runbook and then import the script to the runbook. The second way is to import the script, which will automatically create a new runbook if the runbook does not exist yet. In this section, you’ll learn to use the latter, both in the Portal and PowerShell.

Creating the PowerShell Script

Now, It is time to write the script that will handle the Azure VM scheduled startup. This code will then be imported to the new Azure Automation runbook.

Using your text editor or IDE, copy this code below and save it as C:\ATA\Azure-VM-Schedule-Start-6am.ps1. Read the comments on top of each line to understand what that line of code does.

## Get the Azure Automation Acount Information
$azConn = Get-AutomationConnection -Name 'AzureRunAsConnection'

## Add the automation account context to the session
Add-AzureRMAccount -ServicePrincipal -Tenant $azConn.TenantID -ApplicationId $azConn.ApplicationId -CertificateThumbprint $azConn.CertificateThumbprint

## Get the Azure VMs with tags matching the value '6am'
$azVMs = Get-AzureRMVM | Where-Object {$_.Tags.StartTime -eq '6am'}

## Start VMs
$azVMS | Start-AzureRMVM

That’s it. You’ve created the PowerShell script that will be used by the Azure automation runbook later on.

Creating the Azure Automation Runbook (Azure Portal)

To create a new runbook, in the Azure Portal, go to Automation Accounts and click on your automation account where the runbook will be created. In this example, the automation account name is PS-Demo-AA.

Then go to the Runbooks blade under the Process Automation section, and click on Upload a runbook.

Import a runbook
Import a runbook

The Import a runbook fly-out would appear. Click the Browse button and locate the PowerShell script created earlier with the name C:\ATA\AzureVm6amStartTime.ps1. Once the file is added, click on Create.

Select the runbook script
Select the runbook script

Once the runbook import process is done, you should see the new Azure-VM-Schedule-Start-6am runbook listed in the automation account.

A new runbook is created
A new runbook is created

When you click on the new Azure-VM-Schedule-Start-6am runbook, the runbook properties page will open. Click on the Edit button to confirm that your code was imported.

The new runbook properties
The new runbook properties

As you can see in the below screenshot, the PowerShell script is automatically imported into the runbook.

PowerShell runbook code
PowerShell runbook code

Creating the Azure Automation Runbook (Azure PowerShell)

After saving the PowerShell script name Azure-VM-Schedule-Start-6am.ps1, the next step is to import the script into a new runbook.

The code below will import the script C:\ATA\Azure-VM-Schedule-Start-6am.ps1 into a new PowerShell runbook named Azure-VM-Schedule-Start-6am. Copy the code below and run it in PowerShell.

$runBookSplat = @{
    Name                  = 'Azure-VM-Schedule-Start-6am'
    ResourceGroupName     = 'ATA'
    AutomationAccountName = 'PS-Demo-AA'
    Path                  = 'C:\ATA\Azure-VM-Schedule-Start-6am.ps1'
    Type                  = 'PowerShell'
    Force                 = $true
}
Import-AzAutomationRunbook @runBookSplat

After running the code above, the screenshot below shows a similar result.

Import and create a new PowerShell runbook
Import and create a new PowerShell runbook

Testing the Azure Automation Runbook (Azure Portal)

Runbooks are created as a draft by default. This allows you more time to test your runbook before finally publishing it.

To test the runbook, open the runbook Azure-VM-Schedule-Start-6am in the Edit PowerShell Runbook in the Portal. Then, click on the Test pane button.

Click the Test pane button
Click the Test pane button

Once the Test pane is open, click on the Start button to start the testing. Wait until the runbook testing is completed, and you should see the output stream returned.

Testing the PowerShell runbook
Testing the PowerShell runbook

As you can see from the result above, the runbook test was completed without errors. Furthermore, when you check the list of VMs that are the targets of this runbook, those VMs should now be started.

The Azure virtual machines are started using the automation runbook
The Azure virtual machines are started using the automation runbook

Publishing and Scheduling the Runbook

So you have created the runbook and made sure that the runbook works as intended by running a test. What’s left now is to ensure that the runbook is published in Azure. It is scheduled to run daily at 06:00.

In Azure Automation, a schedule is also a shared resource or an asset. Assets can be used or linked with one or more runbooks. Suffice to say, creating a schedule is not the same as assigning a schedule to a runbook. A schedule can only link to a runbook that is published, not draft.

In the next sections, you’ll learn how to create a schedule, publish a runbook, and link the schedule to the published runbook.

Creating a Schedule (Azure Portal)

In this example, to create a schedule, go to your Automation Account in the Azure Portal, such as PS-Demo-AA. Next, go to Schedules under the Shared Resources section. Once the Schedules blade is open, click on the Add a schedule button.

The Add a schedule button
The Add a schedule button

The New schedule fly-out should appear at the right-most part of the page. Enter the details of the new schedule to create. In this example, the schedule being created is as follows.

  • Name: Azure VM Scheduled Startup 6AM Daily
  • Starts: August 24, 2020 6:00 AM
  • Time Zone: Philippines
  • Recurrence: Recurring
  • Recur every: 1 day
  • Set expiration: No

Once you’ve entered your desired schedule details, click on Create.

The New schedule fly-out
The New schedule fly-out

A new schedule would then appear in the list of schedules indicating that the schedule creation was successful.

The new schedule asset is created in the Azure Portal
The new schedule asset is created in the Azure Portal

Creating a Schedule (Azure PowerShell)

If you’d like to create the new schedule asset using PowerShell instead of the Portal, use the code below. Change the values of the schedule properties as you see fit.

# Build the schedule parameters
$azSchedule = @{
    Name = 'Azure VM Scheduled Startup 6AM Daily'
    TimeZone = 'Asia/Manila'
    StartTime = (Get-Date 'August 24, 2020 06:00:00 +08:00')
    DayInterval = 1
    ResourceGroupName = 'ATA'
    AutomationAccountName = 'PS-Demo-AA'
}
# Create the schedule
New-AzAutomationSchedule @azSchedule

Note: Notice that the TimeZone value is already provided. Yet the StartTime still includes the time offset for that timezone. This is because the StartTime value does not automatically consider the TimeZone when the schedule is being created for the first time.

After running the above code in PowerShell, you would expect to see a similar result, as shown in the screenshot below.While in the Azure Portal, navigate to the runbook, and open it in Edit mode.

The new schedule asset is created in Azure PowerShell
The new schedule asset is created in Azure PowerShell

Publishing the Runbook (Azure Portal)

To publish a runbook in the Azure Portal, navigate to the runbook and open it in Edit mode.

Open the runbook in Edit mode.
Open the runbook in Edit mode.

Once the runbook is opened in the editor, click on the Publish button. You may be prompted whether or not to proceed with publishing the runbook. Click Yes to continue.

Publish the runbook
Publish the runbook

After you’ve published the runbook, you’ll notice that the runbook’s status changed from New to Published.

Runbook is published using Azure Portal
Runbook is published using Azure Portal

Publishing the Runbook (Azure PowerShell)

Runbooks can be published using Azure PowerShell, too. You’ll need to use the code below, just make sure to change the parameter values of -Name, -AutomationAccountName, and -ResourceGroup to match your values.

Publish-AzAutomationRunbook `
    -Name 'Azure-VM-Schedule-Start-6am' `
    -AutomationAccountName 'PS-Demo-AA' `
    -ResourceGroup ATA

The below image shows the expected output after running the Publish-AzAutomationRunbook command above.

Runbook is published using Azure PowerShell
Runbook is published using Azure PowerShell

Now you’ve published the runbook. You’re now ready to link the runbook to a schedule.

Adding a Schedule to the Runbook (Azure Portal)

The schedule that was previously created name Azure VM Scheduled Startup 6AM Daily can now be linked to the published runbook. To link the schedule, click on the Link to schedule button while in the runbook’s Overview blade.

Link to schedule
Link to schedule

Then, click on Link a schedule to your runbook. A list of available schedules will be shown.

Link a schedule to your runbook
Link a schedule to your runbook

Next, click on the schedule to be linked to the runbook, such as the Azure VM Scheduled Startup 6AM Daily in this example.

Select the schedule from the list
Select the schedule from the list

After choosing the schedule, click on the OK button to finish linking the schedule to the runbook.

Link the runbook to a schedule using the Azure Portal
Link the runbook to a schedule using the Azure Portal

Adding a Schedule to the Runbook (Azure PowerShell)

Using the command below achieves the same result of linking a schedule to a runbook when done in the Azure Portal. Make sure to change the -Name, -ScheduleName, -AutomationAccountName, and -ResourceGroupName parameter values appropriately.

Register-AzAutomationScheduledRunbook `
    -Name 'Azure-VM-Schedule-Start-6am' `
    -ScheduleName 'Azure VM Scheduled Startup 6AM Daily' `
    -AutomationAccountName 'PS-Demo-AA' `
    -ResourceGroupName 'ATA'

And as quick as that, your runbook is now linked to the selected schedule, as you can see from the result below.

Link the runbook to a schedule using Azure PowerShell
Link the runbook to a schedule using Azure PowerShell

That’s it. You’re Azure VM scheduled startup is now configured!

Summary

After reading this article, you have learned how to use Tags and Azure Automation to create a runbook to automate Azure virtual machines’ start-up at a set schedule. You’ve learned the step-by-step process:

  • Assigning tags to virtual machines.
  • Creating, testing, and publishing a draft runbook.
  • Creating a schedule and assigning the schedule to the published runbook.

Best of all, you’ve learned to do all these steps in both the Azure Portal and Azure PowerShell.

With the knowledge you’ve gained in this article, maybe you’re next step is to create a runbook to shut down or stop Azure VMs on schedule, too.

Further Reading

Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.

Explore ATA Guidebooks

Looks like you're offline!