通过REST API创建Databricks集群时发生异常

问题描述

我可以使用Postman中的以下内容通过REST API成功创建Databricks集群:

POST /api/2.0/clusters/create HTTP/1.1
Host: adb-xxxxxxxxxxxxxxxx.xx.azuredatabricks.net
Authorization: Bearer eyJ <REMOVED> EJA
Content-Type: application/json

{
  "cluster_name": "xxxxxxx-xxxxx-xx-x-xxx-##-xxxxxxx-####","spark_version": "5.5.x-scala2.11","node_type_id": "Standard_DS3_v2","autoscale" : {
    "min_workers": 2,"max_workers": 10
  },"autotermination_minutes": 30
}

当我将以上内容转换为与PowerShell的Invoke-RestMethod一起使用时,我得到了WebException。在Windows PowerShell ISE中运行脚本(以管理员身份运行)时,将得到以下结果:

The Remote Server returned an error: (400) Bad Request.
at <ScriptBlock>,<No file>: line 91
System.Net.WebException: The Remote Server returned an error: (400) Bad Request.
   at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.GetResponse(WebRequest request)
   at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.ProcessRecord()

PowerShell中生成的Azure AD令牌与Postman中成功使用的令牌相同。这个问题似乎与错误的令牌无关。

以下是导致异常的PowerShell:

<SCRIPT>

... API calls re: AAD Token omitted ...

Write-Host "Create Databricks Cluster"

$body = @{
    cluster_name = "xxxxxxx-xxxxx-xx-x-xxx-##-xxxxxxx-####"
    spark_version = "5.5.x-scala2.11"
    node_type_id = "Standard_DS3_v2"
    autoscale = @{
        min_workers = 2
        max_workers = 10
    }
    autotermination_minutes = 30
}

$headers = @{
    "Authorization"="Bearer " + "$apiKey";
    "Content-Type"="application/json";
}

$uri = "$uriroot/2.0/clusters/create"

Write-Host $uri
Write-Host $headers

try { $response = Invoke-RestMethod -Method 'Post' -Uri $uri -Headers $headers -Body $body }
catch { 
    Write-Host $_
    Write-Host $_.ScriptStackTrace
    Write-Host $_.Exception
    Write-Host $_.ErrorDetails
}

Write-Host $response

</SCRIPT>

Postman中缺少什么PowerShell版本?

解决方法

这是我找到的解决方案。在传递给ConvertTo-Json命令行参数的$body变量上使用-Body

try { $response = Invoke-RestMethod -Method 'Post' -Uri $uri -Headers $headers -Body (ConvertTo-Json $body) }