Search code examples
jenkinsjenkins-pipeline

How to get username password stored in Jenkins credentials separately in jenkinsfile


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.


Solution

  • 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'
    }