Jenkins Credentials Store Access via Groovy Jenkins Credentials Store Access via Groovy git git

Jenkins Credentials Store Access via Groovy


This works. It gets the credentials rather than the store.

I didn't write any error handling so it blows up if you don't have a credentials object set up (or probably if you have two). That part is easy to add though. The tricky part is getting the right APIs!

def getPassword = { username ->    def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(        com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials.class,        jenkins.model.Jenkins.instance    )    def c = creds.findResult { it.username == username ? it : null }    if ( c ) {        println "found credential ${c.id} for username ${c.username}"        def systemCredentialsProvider = jenkins.model.Jenkins.instance.getExtensionList(            'com.cloudbees.plugins.credentials.SystemCredentialsProvider'            ).first()      def password = systemCredentialsProvider.credentials.first().password      println password    } else {      println "could not find credential for ${username}"    }}getPassword("jeanne")


The official solution n the jenkins wiki

Printing a list of all the credentials in the system and their IDs.

def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(        com.cloudbees.plugins.credentials.Credentials.class,        Jenkins.instance,        null,        null);for (c in creds) {    println(c.id + ": " + c.description)}


If you just want to retrieve the credentials for a given credentials ID, the simplest way is to use the withCredentials pipeline step to bind credentials to variables.

withCredentials([usernamePassword( credentialsId: 'myCredentials',                      usernameVariable: 'MYUSER', passwordVariable: 'MYPWD' )]) {     echo "User: $MYUSER, Pwd: $MYPWD" }