我最近收到了关于启用系统分配的有用指导 以及 Azure 虚拟机 (VM) 的用户分配的托管标识 通过REST API 调用。现在,我正在寻求帮助以使用 PowerShell 的 Invoke-RestMethod 复制此过程。
这是我用来实现此目的的 REST API 调用:
PATCH https://management.azure.com/subscriptions/<SUBSCRIPTION
ID>/resourceGroups/<RESOURCE
GROUP>/providers/Microsoft.Compute/virtualMachines/<VM
NAME>?api-version=2017-12-01 HTTP/1.1
{
"identity":{
"type":"SystemAssigned,UserAssigned",
"identityIds":[
"/subscriptions/<SUBSCRIPTION ID>/resourcegroups/<RESOURCE
GROUP>/providers/Microsoft.ManagedIdentity/userAssignedIdentities/<USER
ASSIGNED IDENTITY NAME>"
]
}
}
有人可以帮我将其翻译成 PowerShell 脚本吗 使用调用 RestMethod?具体来说,我需要有关如何进行的指导 使用服务主体合并身份验证,构造 JSON 负载,并发出 PATCH 请求。
任何帮助或示例将不胜感激。谢谢!
您可以使用以下 PowerShell 脚本通过使用
Invoke-RestMethod
调用 REST API 来启用这两种身份:
# Authentication
$tenantId = "tenantId"
$clientId = "appId"
$clientSecret = "secret"
$tokenEndpoint = "https://login.microsoftonline.com/$tenantId/oauth2/token"
$body = @{
"grant_type" = "client_credentials"
"client_id" = $clientId
"client_secret" = $clientSecret
"resource" = "https://management.azure.com/"
}
$response = Invoke-RestMethod -Method Post -Uri $tokenEndpoint -Body $body
$accessToken = $response.access_token
# Define variables
$subscriptionId = "subId"
$resourceGroup = "Sri"
$vmName = "testvm"
$userAssignedIdentityName = "testusermi"
$apiVersion = "2017-12-01"
# Construct JSON payload
$jsonPayload = @{
"identity" = @{
"type" = "SystemAssigned,UserAssigned"
"identityIds" = @(
"/subscriptions/$subscriptionId/resourcegroups/$resourceGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/$userAssignedIdentityName"
)
}
} | ConvertTo-Json
# Construct PATCH URL with formatted vmName
$patchUrl = "https://management.azure.com/subscriptions/$subscriptionId/resourceGroups/$resourceGroup/providers/Microsoft.Compute/virtualMachines/{0}?api-version=$apiVersion" -f $vmName
# PATCH request
$result = Invoke-RestMethod -Method Patch -Uri $patchUrl -Headers @{
"Authorization" = "Bearer $accessToken"
"Content-Type" = "application/json"
} -Body $jsonPayload
$result
回复:
当我在 Portal 中检查相同内容时,两个身份都在 Azure 虚拟机中成功启用,如下所示:
系统分配的托管身份:
用户分配的托管身份: