Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AzureVMRESTMSI
# 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: https://www.sepago.de/blog/2018/01/16/deallocate-an-azure-vm-from-itself
# Read VM details from Azure VM Instance Metadata
$md = Invoke-RestMethod -Headers @{"Metadata"="true"} -URI http://169.254.169.254/metadata/instance?api-version=2017-08-01
# Save variables from metadata
$subscriptionId = $md.compute.subscriptionId
$resourceGroupName = $md.compute.resourceGroupName
$vmName = $md.compute.name
# 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="https://management.azure.com/"} `
-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 `
https://management.azure.com/subscriptions/$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