Johan Karlberg
Johan Karlberg

Reputation: 109

Access information about pusher in Jenkins GitHub Branch Source plugin commit webhook payload

I'm using the Jenkins GitHub Branch Source plugin together with a GitHub App in an Organization. The integration is working fine and jobs get created and triggered on commit as intended. The webhook is configured through the GitHub App

However, I would like to know who triggered the build. I can see the pushing GitHub account name in the webhook payload sent by GitHub, but I don't know how, or if I can access this information from my pipeline. Is this information available, and if so, how would I go about accessing it?

I'm not seeing any related information in the environment by default

Upvotes: 0

Views: 246

Answers (1)

MaratC
MaratC

Reputation: 6869

You can use GitHub API (need to get token from GitHub with proper permissions) to question the different information about the branch. One piece that may help you is that branch's last commit's author:

    withCredentials([usernamePassword(credentialsId: "github-app",
            passwordVariable: 'TOKEN', 
            usernameVariable: 'APP_ID')]) {

        def orgName = "YOUR_ORG_NAME"
        def projectName = "YOUR_PROJECT_NAME"
        def branch_name = env.CHANGE_ID ? env.CHANGE_BRANCH : env.BRANCH_NAME

        def url = "https://api.github.com/repos/${orgName}/${projectName}/branches/${branchName}"
        def headers = ' -H "Content-Type: application/json" \
                        -H "Authorization: token $TOKEN" '
        def the_email = sh (label: "Get Author email",
                returnStdout: true,
                script: "curl -s ${url} ${headers} | \
                      jq -r .commit.commit.author.email").trim().toLowerCase()
        println "the_email is ${the_email}"
    }

The "author" object looks like this:

{
  "name": "GitHubUser",
  "email": "[email protected]",
  "date": "2022-06-28T10:20:12Z"
}

Naturally, there is more than one way to trigger a build. For example, it can also be triggered manually. In that case, the above won't work, and you need to search inside the "causes" of the build.

Upvotes: 1

Related Questions