Comment pull requests from Jenkins

Rationale TL;DR

Let’s suppose you would like to comment a PR from a Jenkins pipeline.

The solution

Using the pipeline-github plugin

We can install the pipeline-github plugin. This plugin will provide you additional Groovy methods you can consume from your pipeline. You can find that plugin in its site.

With that plugin, you can use the commenter with a block like this:

stage('TerraformPipeline - Comment the pr') {
    when {
        expression {
            env.CHANGE_ID != null
        }
    }
    steps {
        script {
            pullRequest.comment('Pull request seems to validate just fine.')
        }
    }
}

In this case, I need to check whether the build was triggered because of a PR or not.

Using the cloudposse/github-commenter docker container

Another option would be to use this docker image. I’ve just integrated it into a Jenkins shared library. The method I use in my library looks like this:

#!/usr/bin/env groovy

import org.gusi.Constants

def call(String GITHUB_TOKEN, String REPO, String COMMENT_TYPE, String CHANGE_ID, String REGEX, String FILE) {
    OUTPUT = sh(script: """docker run -i --rm -e GITHUB_TOKEN=${GITHUB_TOKEN} \
                             -e GITHUB_OWNER=gustauperez \ 
                             -e GITHUB_REPO=${REPO}\
                             -e GITHUB_COMMENT_TYPE=${COMMENT_TYPE} \
                             -e GITHUB_PR_ISSUE_NUMBER=${CHANGE_ID} \
                             -e GITHUB_DELETE_COMMENT_REGEX=\"${REGEX}\" \
                             -e GITHUB_COMMENT_FORMAT=\"My comment:<br/>\" \
                             -e GITHUB_COMMENT=\"\$(cat ${WORKSPACE}/${FILE})\" cloudposse/github-commenter:latest """, returnStdout:true).trim()
    return OUTPUT
 }

In my pipelines, I call that method with:

prCommenter(GITHUB_TOKEN, "terraform_infra", "pr", env.CHANGE_ID, "Refreshing Terraform state in-memory prior to plan..", "terraform.out")

Take into account the GITHUB_DELETE_COMMENT_REGEX argument. That one is important because it will remove any previous comment maching that regex pattern. That works cool because you can run multiple times the pipeline and avoid having multiple comments that probably wouldn’t interest you at all.