CodeMed
CodeMed

Reputation: 9181

Use credentials to make API calls from a Jenkinsfile

What is a secure way to use credentials to make REST API calls from a Jenkinsfile?

For example, the following would not be secure because the username and password are exposed in code:

sh "curl -D- -u username:password -X GET -H 'Content-Type: application/json' http://<ip-of-server-with-rest-api>/path/to/api/endpoint"

Upvotes: 1

Views: 3434

Answers (1)

Mikhail Naletov
Mikhail Naletov

Reputation: 285

You should use Credentials Binding Plugin

Here is an example:

withCredentials([usernamePassword(credentialsId: 'amazon', 
 usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
 // available as an env variable, but will be masked if you try to print it 
  out any which way
 // note: single quotes prevent Groovy interpolation; expansion is by 
  Bourne Shell, which is what you want
  sh 'echo $PASSWORD'
 // also available as a Groovy variable
  echo USERNAME
 // or inside double quotes for string interpolation
  echo "username is $USERNAME"

 sh "curl -D- -u $USERNAME:$PASSWORD -X GET -H 'Content-Type: application/json' http://<ip-of-server-with-rest-api>/path/to/api/endpoint"
}

Your credentials will be hidden in Console Output.

Upvotes: 3

Related Questions