VSTS构建步骤中的Powershell Invoke-RestMethod失败,错误417

时间:2018-02-16 09:52:32

标签: powershell azure-pipelines-build-task lametric

我们自己买了一个Lametric时钟(www.lametric.com),支持显示通过Web-API发送给它的消息。我们希望将其集成到CI / CD队列中。为此我们编写了一个Powershell脚本,它将发送一个指定的通知。在本地执行时,此脚本可以正常工作。从(本地)VSTS Build Agent执行时,它失败并显示状态码417.

这是powershell脚本:

Param (
    [Parameter(mandatory=$true)]
    [string] $BuildName,
    [Parameter(mandatory=$false)]
    [string] $Message
)


$Payload = '{"priority":"critical","icon_type":"alert","lifeTime":2000,"model":{"frames":[{"icon":"555","text":"' + $BuildName + ' BUILD FAILED! ' + $Message + '"}],"sound":{"category":"alarms","id":"alarm6","repeat":2},"cycles":0}}'

$request = @{uri = 'http://<ip-address>:8080/api/v2/device/notifications';
              Method = 'POST';
              Headers = @{Authorization = 'Basic <base64-encoded-credentials>='; "Content-Type" = 'application/json' }
       Body = $Payload
  }

invoke-restmethod @request

有人能指出我们正确的方向,为什么我们在构建步骤中遇到这个问题,而不是在本地?

更新1:

如果我删除所有变量,它仍然会失效。

更新2:

  • Invoke-RestMethod更改为Invoke-WebRequest不会有所不同。
  • 调用GET请求
  • 调用POST请求失败,错误417

1 个答案:

答案 0 :(得分:1)

我似乎找到了问题的解决方案。看到发送带有GET选项的-UseBasicParsing请求工作正常,我尝试将这两个请求一个接一个地组合在一起。如果它们分为两个单独的构建步骤,则无效。

但是,一旦我发送了GET请求,并按照上述POST请求进行了跟进,就会神奇地发挥作用。我不知道,为什么会这样,但这是我们目前的解决方案:

Param (
        [Parameter(mandatory=$true)]
        [string] $BuildName,
        [Parameter(mandatory=$false)]
        [string] $Message
)

$request = @{uri = 'http://<ip-address>:8080/api/v2';
            Method = 'GET';
            Headers = @{Authorization = 'Basic <base64-encoded-credentials>'; }
  }

invoke-webrequest -UseBasicParsing @request

$Payload = '{"priority":"critical","icon_type":"alert","lifeTime":2000,"model":{"frames":[{"icon":"555","text":"' + $BuildName + ' BUILD FAILED! ' + $Message + '"}],"sound":{"category":"alarms","id":"alarm6","repeat":2},"cycles":0}}'

$request = @{uri = 'http://<ip-address>:8080/api/v2/device/notifications';
            Method = 'POST';
            Headers = @{Authorization = 'Basic <base64-encoded-credentials>'; "Content-Type" = 'application/json' }
            Body = $Payload
  }

invoke-webrequest -UseBasicParsing @request