无法从詹金斯管道中的 GitHub 网络钩子触发器获取有效负载

问题描述

我已经使用以下设置配置了一个 Github 网络钩子: 有效负载网址:https:///github-webhook/ 内容类型:application/x-www-form-urlencoded 事件:推送、拉取请求

我拥有的 Jenkins 工作是一个启用了以下功能的管道工作: 构建触发器:用于 GITScm 轮询的 GitHub 钩子触发器

通过上述配置,我看到响应事件即;在 GitHub 中 push/PR,jenkins 作业被成功触发。在 GitHub 中,在 Web hook 的“Recent Deliveries”下,我看到了有效负载的详细信息和 200 的成功响应。

我正在尝试在 Jenkins Pipeline 中获取有效负载以进行进一步处理。我需要一些详细信息,例如:PR URL/PR 编号、引用类型、分支名称等,以便在 Jenkins 管道中进行条件处理。

我尝试访问“payload”变量(如其他堆栈溢出帖子和可用文档中所述)并将其打印为管道的一部分,但我还没有运气。

所以我的问题是,如何从 Jenkins 管道中的 GitHub 网络钩子触发器获取有效负载

解决方法

不确定这是否可行。

使用我们使用的 GitHub 插件(Pipeline Github),PR 编号存储在变量 CHANGE_ID 中。 给定 PR 编号,PR URL 很容易生成。分支名称存储在变量 BRANCH_NAME 中。在拉取请求的情况下,全局变量 pullRequest 被填充 with lots of data

可以使用他们的 API 从 Github 获取缺失的信息。这是检查 PR 是否“落后”的示例,您可以根据具体要求对其进行修改:

def checkPrIsNotBehind(String repo) {
    withCredentials([usernamePassword(credentialsId: "<...>",passwordVariable: 'TOKEN',usernameVariable: 'USER')]) {
        def headers = ' -H "Content-Type: application/json" -H "Authorization: token $TOKEN" '
        def url = "https://api.github.com/repos/<...>/<...>/pulls/${env.CHANGE_ID}"
        def head_sha = sh (label: "Check PR head SHA",returnStdout: true,script: "curl -s ${url} ${headers} | jq -r .head.sha").trim().toUpperCase()
        println "PR head sha is ${head_sha}"
        
        headers = ' -H "Accept: application/vnd.github.v3+json" -H "Authorization: token $TOKEN" '
        url = "https://api.github.com/repos/<...>/${repo}/compare/${pullRequest.base}...${head_sha}"
        def behind_by = sh (label: "Check PR commits behind",script: "curl -s ${url} ${headers} | jq -r .behind_by").trim().toUpperCase()
        
        if (behind_by != '0') {
            currentBuild.result = "ABORTED"
            currentBuild.displayName = "#${env.BUILD_NUMBER}-Out of date"
            error("The head ref is out of date. Please update your branch.")
        }
    }
}