如何在PowerShell中使用RESTful API在Azure中创建资源组?

时间:2017-06-30 20:50:38

标签: rest powershell azure

我想使用REST API调用创建Azure资源组,但我似乎无法正确使用语法。这就是我所拥有的:

$validateResourceGroupUri = 'https://management.azure.com/subscriptions/SUBSCRIPTION_ID/resourceGroups/' + $resourceGroupName + '/?api-version=2015-01-01'

try { $trapValidateResponse = Invoke-RestMethod -Method PUT -Headers $armHeaders -Uri $validateResourceGroupUri -Body $deploymentTemplate }
catch { throw $_ }

其中:

$deploymentTemplate = JSON deployment template (obviously)

$resourceGroupName = user-inputted RG name to be created

$armHeaders = @{ 'Authorization' = "Bearer $token"; 'Content-Type' = "Application/json" }

我觉得这个问题存在于-Body参数中,但我似乎无法在网上找到任何详细说明该调用应包含的内容。我找到了THIS,如果你向下滚动到“创建一个资源组”部分,它会详细介绍一些信息,但不幸的是,我已经找到了所有信息。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

您可以尝试使用以下命令创建新资源组,它适用于我。

##get token
$TENANTID="<your tenantid>"
$APPID="<>"
$PASSWORD="<>"
$result=Invoke-RestMethod -Uri https://login.microsoftonline.com/$TENANTID/oauth2/token?api-version=1.0 -Method Post -Body @{"grant_type" = "client_credentials"; "resource" = "https://management.core.windows.net/"; "client_id" = "$APPID"; "client_secret" = "$PASSWORD" }
$token=$result.access_token

##set subscriptionId and resource group name
$subscriptionId="<your subscriptionId >"
$resourcegroupname="<resource group name>"

$Headers=@{
  'authorization'="Bearer $token"
  'host'="management.azure.com"
}
$body='{
    "location": "northeurope",
     "tags": {
        "tagname1": "test-tag"
    }
 }'
Invoke-RestMethod  -Uri "https://management.azure.com/subscriptions/$subscriptionId/resourcegroups/${resourcegroupname}?api-version=2015-01-01"  -Headers $Headers -ContentType "application/json" -Method PUT -Body $body

enter image description here