在发布成功后尝试发送 JSON Payload 时出现 Jenkins 管道错误

时间:2021-03-14 02:03:42

标签: json jenkins jenkins-pipeline jenkins-groovy payload

在最后一个成功阶段之后,我正在尝试从我在 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 是正确的。

1 个答案:

答案 0 :(得分:2)

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

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

Apart from the single quoted string,它们还有一个次要属性 interpolation

注意在最初的 JSON 负载中,有一个 "$schema" 键吗?使用三重双引号字符串会使 groovy 想要找到一个 schema 变量并使用它的值来构造该负载变量。

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

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