How to get username password stored in Jenkins cre

2020-06-09 05:01发布

问题:

I've stored username and password as credentials in jenkins. Now I would like to use them in my Jenkinsfile.

I am using withCredentials DSL, however, I'm not sure how to get the username password as separate variables so I can use them in my command.

This is what I'm doing:

withCredentials([usernameColonPassword(credentialsId: 'mycreds', variable: 'MYCREDS')]) {
  sh 'cf login some.awesome.url -u <user> -p password'
}

How can I the username and passwork separately? I tried doing ${MYCREDS.split(":")[0]} but that doesn't seem to work.

回答1:

You can use the UsernamePasswordMultiBinding to get credential data in separate values:

withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId:'mycreds',
  usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']
])

So the following should work in your case:

withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId:'mycreds', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) {
  sh 'cf login some.awesome.url -u $USERNAME -p $PASSWORD'
}


回答2:

Here is a tiny bit simpler version of StephenKing's answer

withCredentials([usernamePassword(credentialsId: 'mycreds', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
  sh 'cf login some.awesome.url -u $USERNAME -p $PASSWORD'

}