Trying to create a github pull request using curl on Jenkins on a windows server. Jekins groovy code to create PR:
stage('Git Pull Request') {
steps {
script {
withCredentials([usernamePassword(credentialsId: 'GitHubToken', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
// Create a GitHub pull request
def prResponse = bat (
script: "curl -L -X POST -u $USERNAME:$PASSWORD https://git.company.com/api/v3/repos/vanpa/test_repo/pulls -d \"{\"title\":\"title\", \"body\":\"body\", \"head\":\"delete_test2\", \"base\":\"delete_test1\"}\"",
returnStdout: true)
echo "${prResponse}"
}
}
}
}
This returns below output::
D:\Jenkins\workspace\test 2>curl -L -X POST -u vanpa:**** https://git.company.com/api/v3/repos/vanpa/test_repo/pulls -d "{"title":"title", "body":"body", "head":"delete_test2", "base":"delete_test1"}"
{
"message": "Problems parsing JSON",
"documentation_url": "https://docs.github.com/enterprise-server@3.9/rest/reference/pulls#create-a-pull-request"
}
How to fix this ?
Other solutions for similar problem suggest issues with single quotes on windows. Have removed all the single quotes and only using double quotes.
Hand-rolling JSON parameters in batch script is error prone, as you have found out. In a simple case like this you could probably get away with just fixing your escape characters. Since you have double expansion (first in groovy then in batch script) you need double escaping \\\"
.
Normally you would want to avoid this and use Groovy to deal with JSON, save it to a temp file, and make curl
post that file instead of inline data. The writeJSON
step is provided by the pipeline-utility-steps plugin.
stage('Git Pull Request') {
steps {
script {
withCredentials([usernamePassword(credentialsId: 'GitHubToken', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
// Create a GitHub pull request
def data = [
'title': 'title',
'body': 'body',
'head': 'delete_test2',
'base': 'delete_test1',
]
writeJSON file: 'data.json', json: data
def prResponse = bat (
script: "curl -L -X POST -u $USERNAME:$PASSWORD https://git.company.com/api/v3/repos/vanpa/test_repo/pulls --data @data.json",
returnStdout: true)
echo prResponse
}
}
}
}
Also, expanding $PASSWORD
in groovy is a bad idea and Jenkins have probably pestered you about that already.