Azure Automation Runbook 无法将 webhook 数据解析为 JSON 对象

Azure Automation Runbook unable to parse the webhookdata as a JSON object

这个问题让我很受打击。我请求你回答或给予提示。我 运行 没有选择。

我正在通过 WebHook 在 CPU 高利用率时调用 Azure Runbook。我的问题是运行手册中的数据没有被正确解码。例如,下面一行没有打印任何东西。

 Write-Output $WebHookData.RequestHeader

如果我尝试将数据显式转换为 JSON,就像这样

*$WebhookData = ConvertFrom-Json $WebhookData*

那么就是抛错了

ConvertFrom-Json : Invalid JSON primitive: . At line:6 char:31 + $WebhookData = $WebhookData | ConvertFrom-Json

顺便说一下,我正在尝试使用 Azure 库中提供的运行手册{使用 Azure 自动化垂直扩展 Azure 资源管理器 VM}

我的 Webhook 是从 VM 上创建的警报调用的。

一个非常奇怪的观察:

工作 WebHood 示例(在示例中找到){"WebhookName":"test1","RequestBody":" [\r\n {\r\n \"Message\": \"Test Message\"\r\n }\r\n****]****

不工作(从 VM 调用 runbook 时发送的数据):

{"WebhookName":"test2","RequestBody":" {\"schemaId\":\"AzureMonitorMetricAlert\"}}

谢谢

我尝试使用 webhook,脚本 Write-Output $WebHookData.RequestHeader 应该可以正常工作。

如果我使用 ConvertFrom-Json $WebhookData,我可以重现你的问题,不知道为什么会发生,根据 doc$WebhookData 也在 JSON格式,如果被接受,你可以使用ConvertFrom-Json -InputObject $WebhookData.RequestBody,它会正常工作。

我的操作手册:

param
(
    [Parameter (Mandatory = $false)]
    [object] $WebhookData
)

if ($WebhookData) {

    Write-Output $WebhookData.RequestHeader

    $Body = ConvertFrom-Json -InputObject $WebhookData.RequestBody
    Write-Output $Body

} else
    {
        Write-Output "Missing information";
        exit;
    }

我用来发送webhook的powershell脚本:

$uri = "https://s5events.azure-automation.net/webhooks?token=xxxxxxxxxxxx"

$vms  = @(
            @{ Name="vm01";ResourceGroup="vm01"},
            @{ Name="vm02";ResourceGroup="vm02"}
        )
$body = ConvertTo-Json -InputObject $vms
$header = @{ message="StartedbyContoso"}
$response = Invoke-WebRequest -Method Post -Uri $uri -Body $body -Headers $header
$jobid = (ConvertFrom-Json ($response.Content)).jobids[0]

输出:

如果使用带有警报 json 的测试窗格作为输入

,我会遇到同样的问题,使用以下方法获取 webhookdata
if(-Not $WebhookData.RequestBody){

    $WebhookData = (ConvertFrom-Json -InputObject $WebhookData)
}
$RequestBody = ConvertFrom-JSON -InputObject $WebhookData.RequestBody

我遇到了同样的错误。根据我的测试,似乎在执行 runbook 的“测试”时,Webhook 数据以纯文本形式接收,但在远程调用时,它已经格式化为 JSON。这是我涵盖这两种情况的解决方案,到目前为止效果很好...

Param (
    [object] $WebhookData
)
# Structure Webhook Input Data
If ($WebhookData.WebhookName) {
    $WebhookName     =     $WebhookData.WebhookName
    $WebhookHeaders  =     $WebhookData.RequestHeader
    $WebhookBody     =     $WebhookData.RequestBody
} ElseIf ($WebhookData) {
    $WebhookJSON = ConvertFrom-Json -InputObject $WebhookData
    $WebhookName     =     $WebhookJSON.WebhookName
    $WebhookHeaders  =     $WebhookJSON.RequestHeader
    $WebhookBody     =     $WebhookJSON.RequestBody
} Else {
   Write-Error -Message 'Runbook was not started from Webhook' -ErrorAction stop
}