Automating VM Shutdown with Azure Automation PowerShell Runbooks and Managed Identity

In this blog post, we will discuss how to use Azure Automation PowerShell runbooks to stop a virtual machine (VM) with a managed identity.

Azure Automation is a cloud-based automation service that allows you to automate tasks across Azure and non-Azure environments.

Managed Identity

Before we start, let’s understand what a managed identity is. Managed identities are a feature of Azure Active Directory that provides an identity for Azure resources to use to authenticate with Azure services. This allows you to avoid the need to store and manage secrets, such as passwords or certificates, for your applications.

PowerShell Code

In the PowerShell runbook, you need to write a script that will stop the VM using the managed identity credentials. Here is an example script. Change the Vars section to match your environment details

# Ensures you do not inherit an AzContext in your runbook
Disable-AzContextAutosave -Scope Process

# Connect to Azure with system-assigned managed identity
$AzureContext = (Connect-AzAccount -Identity).context

# Set and store context
$AzureContext = Set-AzContext -SubscriptionName $AzureContext.Subscription -DefaultProfile $AzureContext
Set-AzContext -SubscriptionId "azure-subbscription-id" 

# Vars

stop-AzVM -ResourceGroupName $rg_name -Name $vmname -force -Confirm:$false -verbose

Success! You're on the list.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.