在 post 成功后尝试发送 JSON 负载时 Jenkins 管道错误

Jenkins Pipeline Error while trying to send JSON Payload after post success

我正在尝试在最后一个成功阶段后从我在 Jenkins 上的管道发送一个自定义 JSON 负载,如下所示:

  post {
        success {
            script {
                def payload = """
{
    "type": "AdaptiveCard",
    "body": [
        {
            "type": "TextBlock",
            "size": "Medium",
            "weight": "Bolder",
            "text": "SonarQube report from Jenkins Pipeline"
        },
        {
            "type": "TextBlock",
            "text": "Code was analyzed was successfully.",
            "wrap": true,
            "color": "Good",
            "weight": "Bolder"
        }
    ],
    "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
    "version": "1.3"
}"""
                httpRequest httpMode: 'POST',
                        acceptType: 'APPLICATION_JSON',
                        contentType: 'APPLICATION_JSON',
                        url: "URL",
                        requestBody: payload
            }
        }
    }
}

但是我得到一个错误

Error when executing success post condition:
groovy.lang.MissingPropertyException: No such property: schema for class: groovy.lang.Binding
    at groovy.lang.Binding.getVariable(Binding.java:63)

我正在使用可用于 Jenkins 的 HTTP 请求插件,JSON 有效负载的格式对于 MS Teams 是正确的。

问题实际上是 groovy 语法错误。您可以通过添加 def payload = ... 语句轻松地在 https://groovy-playground.appspot.com/ 之类的内容中进行检查。

在groovy中有多种获取多行字符串的方法:

Apart from the single quoted string, they also have a secondary property which is interpolation

请注意在初始 JSON 有效载荷中,有一个 "$schema" 密钥?使用三重双引号字符串使得 groovy 想要找到一个 schema 变量并使用它的值来构造该有效负载变量。

您有两个不同的解决方案:

  1. 使用 triple single quoted string - 只需将 """ 更新为 '''
  2. 转义变量 - 只需将 "$schema" 更新为 "$schema"(使 $ 成为文字 $ 而不是用作插值前缀)