0

We have a pipeline where we need to invoke external API with Authorization header, whose value comes from Jenkins secret, which has been pre-configured.

When implemented as below, Jenkins complains for string interpolation.

withCredentials([string(credentialsId: '<SECRETNAME>', variable: 'Token')]) { 
  sh """curl --location --request POST 'https://abc.example.com/api/endpoint' \
  --header 'Authorization: Bearer ${Token}' \
  --header 'Content-Type: application/json' \
  --data-raw ${payload}""

We have tried will single quotes for sh and double quotes but nothing works out. How it can be handled here?

Avik Aggarwal
  • 599
  • 7
  • 28

1 Answers1

1

Jenkins doesn't want you to interpolate passwords in the code but rather pass them as environment variables to the shell and let the shell command extract them, that is possible only for parameters that are loaded into the shell execution environment.
In declarative pipelines loading parameters and secrets into shell environment can be done using the environment directive and for scripted pipelines loading secrets can be done via the withCredentials keyword and loading regular parameters can be done via the 'withEnv` keyword.

In your case you have the Token parameter which is loaded into environment by the withCredentials step and the payload parameter which is probably not, so you are mixing two type of parameter contexts, more information on this is available in the Answer for this question.

To solve it you have two options.
The first option is to load the payload into the environment of the shell and use a single quoted groovy string:

withEnv(["PAYLOAD=${payload}"]) {
   withCredentials([string(credentialsId: '<SECRETNAME>', variable: 'Token')]) {
       sh '''curl --location --request POST "https://abc.example.com/api/endpoint" \
     --header "Authorization: Bearer $Token" \
     --header "Content-Type: application/json" \
     --data-raw $PAYLOAD'''
   }
}

Second option is to separate the construction of the string into two types, and handle each section with the relevant method:

withCredentials([string(credentialsId: '<SECRETNAME>', variable: 'Token')]) {
   sh '''curl --location --request POST "https://abc.example.com/api/endpoint" \
     --header "Authorization: Bearer $Token" \
     --header "Content-Type: application/json" \
     --data-raw ''' + payload
}
Noam Helmer
  • 5,310
  • 1
  • 9
  • 29