Search code examples
jenkinsjenkins-pluginsjenkins-groovy

Jenkins - Pass variable from groovy to shell with single quotes


I have a step in Jekins, where I execute curl command. To use a credentials TOKEN, I had to put my shell script into triple single quotes, otherwise I would get error: solution: either escape a literal dollar sign "\$5" or bracket the value expression "${5}" @ line 18, column 33.

But now when using triple single quotes, I cant access my apiUrl variable from shell.

withCredentials([string(credentialsId: 'TOKEN', variable: 'TOKEN']) {
    def exampleUrl = "https://example.com"
    sh '''
    #!/usr/bin/env bash

    RESPONSE_CODE=$(curl -o body.txt --write-out "%{http_code}" --request GET \
    --url $exampleUrl \
    --header "accept: application/json" \
    --header "authorization: Token $TOKEN")
    '''
}

Is there a more elegant solution to this, than using environment variables, so that I can access credentials TOKEN and variable exampleUrl?

Thank you


Solution

  • You can set them as environment variables before the sh block, then you should be able to access them.

    env.exampleUrl = "https://example.com"