Jenkins Credentials Store Access via Groovy

后端 未结 3 781
长情又很酷
长情又很酷 2021-01-31 09:35

I have found a way to access the credentials store in Jenkins:

def getPassword = { username ->
    def creds = com.cloudbees.plugins.credentials.CredentialsPr         


        
相关标签:
3条回答
  • 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)
    }
    
    0 讨论(0)
  • 2021-01-31 10:23

    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" 
    }
    
    0 讨论(0)
  • 2021-01-31 10:36

    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")
    
    0 讨论(0)
提交回复
热议问题