使用PowerShell Invoke-RestMethod复现Azure VM托管身份配置REST API
PowerShell Script to Enable System-Assigned and User-Assigned Managed Identity for Azure VM
Prerequisites
- You need a service principal with Contributor role on the VM's resource group (or higher permissions).
- Have the service principal's client ID, client secret, and tenant ID handy.
1. Authenticate with Service Principal to Get Access Token
First, retrieve an access token for the Azure Management API using your service principal credentials:
# Replace these variables with your service principal details $tenantId = "<YOUR TENANT ID>" $clientId = "<YOUR SERVICE PRINCIPAL CLIENT ID>" $clientSecret = "<YOUR SERVICE PRINCIPAL CLIENT SECRET>" # Get access token $tokenUri = "https://login.microsoftonline.com/$tenantId/oauth2/token" $tokenBody = @{ grant_type = "client_credentials" client_id = $clientId client_secret = $clientSecret resource = "https://management.azure.com/" } $tokenResponse = Invoke-RestMethod -Uri $tokenUri -Method Post -Body $tokenBody $accessToken = $tokenResponse.access_token
2. Construct the JSON Request Body
Define the request body matching your original REST API payload. Use a PowerShell here-string to format the JSON:
# Replace these variables with your VM and identity details $subscriptionId = "<SUBSCRIPTION ID>" $resourceGroup = "<RESOURCE GROUP>" $vmName = "<VM NAME>" $userAssignedIdentityId = "/subscriptions/$subscriptionId/resourcegroups/$resourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/<USER ASSIGNED IDENTITY NAME>" # Build JSON request body $requestBody = @" { "identity": { "type": "SystemAssigned,UserAssigned", "identityIds": [ "$userAssignedIdentityId" ] } } "@
3. Send the PATCH Request to Update the VM
Use Invoke-RestMethod to send the PATCH request with the access token and request body:
# Build the API endpoint URL $apiUrl = "https://management.azure.com/subscriptions/$subscriptionId/resourceGroups/$resourceGroup/providers/Microsoft.Compute/virtualMachines/$vmName`?api-version=2017-12-01" # Send the PATCH request try { $response = Invoke-RestMethod -Uri $apiUrl -Method Patch -Headers @{Authorization = "Bearer $accessToken"} -Body $requestBody -ContentType "application/json" Write-Host "Managed identity enabled successfully for VM: $vmName" Write-Output $response } catch { Write-Host "Error updating VM identity: $_" }
Notes
- Ensure all placeholder values (enclosed in
<>) are replaced with your actual Azure resource details. - The
api-versionis set to2017-12-01to match your original REST API request; you can update this to a newer version if needed. - If you only want system-assigned identity, set
typeto"SystemAssigned"and remove theidentityIdsarray.
内容的提问来源于stack exchange,提问作者Dhivyesh
相关产品推荐
相关产品推荐

