A Jenkins pipeline for creating & merging pull requests in Bitbucket
Following on from using Python to automate the creation of pull requests and merges.
Introduction
This post will cover integrating the Python script into a Jenkins pipeline.
The different parts of the Jenkins pipeline in Groovy are shown below.
Credentials
The Bitbucket username/password are stored within the Jenkins credentials. We shall use this to pass into the Groovy script via UsernamePasswordMultiBinding
Parameters
Giving the user options to either create/merge a pull request.
booleanParam(defaultValue: true, description: 'Create Pull-Request', name: 'CREATE_PR')
booleanParam(defaultValue: true, description: 'Merge Pull-Request', name: 'MERGE_PR')
// Bitbucket credentials
string(defaultValue: '####', description: 'Stash credential id', name: 'STASH_CRED_VAL')
Functions
Adding functions inside the Jenkins pipeline helps in not only visibility but maintainability of the Groovy script.
Creating a pull request
def createPullRequest(){
withCredentials([
[$class: 'UsernamePasswordMultiBinding', credentialsId: "${params.STASH_CRED_VAL}",
usernameVariable: 'BITBUCKET_USERNAME', passwordVariable: 'BITBUCKET_PASSWORD']
]) {
script {
sh "python merge.py \
--username '$BITBUCKET_USERNAME' \
--password '$BITBUCKET_PASSWORD' \
--operation 'create-pr1' \
--settings './resources/pr.settings'"
}
}
}
Merging a pull request
def mergePullRequest1(){
withCredentials([
[$class: 'UsernamePasswordMultiBinding', credentialsId: "${params.STASH_CRED_VAL}",
usernameVariable: 'BITBUCKET_USERNAME', passwordVariable: 'BITBUCKET_PASSWORD']
]) {
script {
sh "python merge.py \
--username '$BITBUCKET_USERNAME' \
--password '$BITBUCKET_PASSWORD' \
--operation 'merge-pr1' \
--settings './resources/pr.settings'"
}
}
}