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!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.
- Since this article is about Azure VMs, you must have access to an Azure subscription. You can request for a free Azure tenant if you do not have one yet.
- You should have one or more Azure VMs provisioned in your tenant. These are the VMs that will be the target of this automation. (see: Create a Windows virtual machine in Azure).
- You must have an Azure Automation Account with an Azure Run As account already prepared. If you don’t have this yet, learn how to create one when you go to Create a new Automation account in the Azure portal.
- The Azure PowerShell module must be installed. If you don’t have this yet, please go to the Install the Azure PowerShell module page for more information.
- You must have established an Azure session using PowerShell (see: Connect-AzAccount).
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.
Then, as the Assign tags fly-out appears, enter this new tag’s Name and Value as StartTime:6am. Then click on Save.
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.
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.
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.
Once the runbook import process is done, you should see the new Azure-VM-Schedule-Start-6am runbook listed in the automation account.
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.
As you can see in the below screenshot, the PowerShell script is automatically imported into the runbook.
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.
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.
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.
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.
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 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.
A new schedule would then appear in the list of schedules indicating that the schedule creation was successful.
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 theStartTime
still includes the time offset for that timezone. This is because theStartTime
value does not automatically consider theTimeZone
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.
Publishing the Runbook (Azure Portal)
To publish a runbook in the Azure Portal, navigate to the runbook and open it 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.
After you’ve published the runbook, you’ll notice that the runbook’s status changed from New to Published.
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.
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.
Then, click on Link a schedule to your runbook. A list of available schedules will be shown.
Next, click on the schedule to be linked to the runbook, such as the Azure VM Scheduled Startup 6AM Daily in this example.
After choosing the schedule, click on the OK button to finish linking the schedule to the runbook.
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.
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.