Search code examples
jenkinscurlgroovygithub-apijenkins-groovy

Groovy in jenkins - curl to Github Api


Trying to send a request to GitHub API from Groovy:

def res = null

withCredentials([string(credentialsId: 'my-github-token', variable: 'GITAPITOKEN')]) {
    withEnv(["REPO=${repo}", "PRID=${prId}", "LABEL=${label}"]) {
        res = sh (script: 'curl -X PUT -H \\"Authorization: token $GITAPITOKEN\\" -d \\"{\\\\"labels\\\\":[\\\\"$LABEL\\\\"]}\\" https://api.github.com/repos/my-user/$REPO/issues/$PRID/labels', returnStdout: true).trim()
    }
}

println("${res}")

it shows that it executes the following:

curl -X PUT -H "Authorization: token ****" -d "{\"labels\":[\"my-label\"]}" https://api.github.com/repos/my-user/my-repo/issues/1/labels

When I run this command locally (including all the escaped characters) it works perfectly

But on jenkins - this returns

curl: (6) Could not resolve host: token

curl: (6) Could not resolve host: ****"

curl: (3) unmatched close brace/bracket in URL position:

my-label\"]}"

          ^

and:

{

"message": "Not Found",

"documentation_url": "https://docs.github.com/rest/reference/issues#set-labels-for-an-issue"

}

So it seems the header escape is somehow not working - what am I missing?


Solution

  • Try something like below.

    pipeline {
        agent any
    
        stages {
            stage('Hello') {
                steps {
                    script {
                        def repo = 'test'
                        def label = "-d \"{\"labels\":[\"label1\"]}"
                        def prId = "123"
                        def token = "1234567890"
                        withEnv(["REPO=${repo}", "PRID=${prId}", "LABEL=${label}", "GITAPITOKEN=${token}"]) {
                            res = sh (script: 'curl -v -X PUT -H \"Authorization: token $GITAPITOKEN\" $LABEL https://api.github.com/repos/my-user/$REPO/issues/$PRID/labels', returnStdout: true).trim()
                            echo "$res"
                        }
                }
            }
        }
    }
    }