Jenkins: Comment on Bitbucket Pull Request

Viewed 2082

Our Jenkins + Bitbucket cloud integration already works and uses a multi-branch pipeline job to notify Bitbucket about the build status of a pull request.

Now I want to enhance it and add preview environments, for example at pr150.testing.company.com so that we can test a live production build before merging. I planned on using docker-compose to dynamically start/stop the preview environments.

Now, Jenkins needs to comment the Bitbucket pull request with the link to the preview environment. I know that the Bitbucket API supports creating pull request comments.

I imagine comments like this: A Jenkins pull request comment

This example is taken from Jenkins-X

Does any Bitbucket plugin for Jenkins support automatically creating such comments?

Edit: To clarify, a plugin that automatically comments on the pull request would be enough. It's no problem to create the content of the comment on our end.

1 Answers

I couldn't find a plugin but you can execute shell commands as part of the jobs build to do it. Since Jenkins works off commits and not pull requests it's a bit of a faf. You need to get the pull request ID from the branch name using the API first. Using the REST 1.0 API you can do it this way.

BranchName=`echo ${GIT_BRANCH} | sed 's/origin\///'`
PullRequestID=`curl -s --request GET --url '{bitbucket_url}/rest/api/1.0/projects/{project_key}/repos/{repo_key}/pull-requests?State=OPEN&at=refs/heads/'${BranchName}'&direction=OUTGOING' --header 'Content-Type: application/json' -u username:password | sed -n 's/.*"values":\[{"id":\([0-9]*\).*/\1/p'`
echo '{"text": "Here's my comment with hyperlink"}' > comment.json
curl --request POST --url '{bitbucket_url}/rest/api/1.0/projects/{project_key}/repos/{repo_key}/pull-requests/'$PullRequestID'/comments' --header 'Content-Type: application/json' -u username:password -d @comment.json
rm comment.json

Notes:

  • The remote name might not be origin but something project specific. Check the console log to find it out
  • Will need changing for 2.0 API but concept should remain the same
Related