Turn Off Azure VM using Azure Automation

In this blog post, I will show you how I turn on an Azure Virtual Machine with Azure Automation.

Azure Automation

Microsoft Azure Automation allows us to automate and schedule a task in Azure using PowerShell scripts.

Module

To manage virtual machines in Microsoft Azure, I will use the following module.

Az.compute

Runbook

In the runbook, I will use the following script.

Please change the following details to match your environment:

SUBSCRIPTIONID

RESOURCEGROUP

VMNAME

$connection = Get-AutomationConnection -Name AzureRunAsConnection

# Wrap authentication in retry logic for transient network failures
$logonAttempt = 0
while(!($connectionResult) -And ($logonAttempt -le 10))
{
    $LogonAttempt++
    # Logging in to Azure...
    $connectionResult =    Connect-AzAccount `
                               -ServicePrincipal `
                               -Tenant $connection.TenantID `
                               -ApplicationId $connection.ApplicationID `
                               -CertificateThumbprint $connection.CertificateThumbprint

    Start-Sleep -Seconds 1
}
Set-AzContext -SubscriptionId "SUBSCRIPTIONID"
stop-AzVM -ResourceGroupName RGGROUP  -Name VMNAME -force

To start an Azure VM using Azure Automation use this post.

Processing…
Success! You're on the list.

Posted

in

by