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.
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.
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 $rg_name="Resource-group-name" $vmname="VM-Name" stop-AzVM -ResourceGroupName $rg_name -Name $vmname -force -Confirm:$false -verbose
Leave a Reply