Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
# This script will shutdown the Azure VM it's running on
# Requirements: Azure Managed Service Identity (MSI) configured on the VMs in question.
# Permissions: The MSI service principal for the VM needs to be added as Virtual Machine Contributor for it's own VM
# Kudos: This script is inspired from Marcel Meurer's script for shutting down VM from itself:
# Read VM details from Azure VM Instance Metadata
$md = Invoke-RestMethod -Headers @{"Metadata"="true"} -URI
# Save variables from metadata
$subscriptionId = $md.compute.subscriptionId
$resourceGroupName = $md.compute.resourceGroupName
$vmName = $
# Next, using the MSI we will get an access token for the service principal
$response = Invoke-WebRequest -Uri http://localhost:50342/oauth2/token -Method GET -Body @{resource=""} `
-Headers @{Metadata="true"}
# Save the response and access token
$content = $response.Content | ConvertFrom-Json
$ArmToken = $content.access_token
# Using Azure REST API to shutdown and deallocate VM, authenticating with access token from MSI
Invoke-WebRequest -Uri `$subscriptionId/resourceGroups/$resourceGroupName/providers/Microsoft.Compute/virtualMachines/$vmName/deallocate?api-version=2016-04-30-preview `
-Method POST -ContentType "application/json" `
-Headers @{ Authorization ="Bearer $ArmToken"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment