Groovy Script to update Credential password breaks job links

509 views
Skip to first unread message

Bill Hurt

unread,
Jan 6, 2016, 3:44:51 PM1/6/16
to Jenkins Developers
I have a question about the groovy script below:

import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl

def changePassword = { username, new_password ->
    def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
        com.cloudbees.plugins.credentials.common.StandardUsernameCredentials.class,
        Jenkins.instance
    )

    def c = creds.findResult { it.username == username ? it : null }

    if ( c ) {
        println "found credential ${c.id} for username ${c.username}"

        def credentials_store = Jenkins.instance.getExtensionList(
            'com.cloudbees.plugins.credentials.SystemCredentialsProvider'
            )[0].getStore()

        def result = credentials_store.updateCredentials(
            com.cloudbees.plugins.credentials.domains.Domain.global(), 
            c, 
            new UsernamePasswordCredentialsImpl(c.scope, null, c.description, c.username, new_password)
            )

        if (result) {
            println "password changed for ${username}" 
        } else {
            println "failed to change password for ${username}"
        }
    } else {
      println "could not find credential for ${username}"
    }
}

changePassword('BillHurt', 's3crEt!')

The problem I'm having is that when I have jobs that link to any credentials that get updated by the groovy script, those jobs will lose the link and break once the credential gets it's new password. 

The link breaks because each time the password is updated it gets a new ID. I don't observe this behavior if I update the password manually via the UI. 

I think the reason is in the following line:
new UsernamePasswordCredentialsImpl(c.scope, null, c.description, c.username, new_password)

I know basically nothing about scripting in Jenkins, but this looks a lot like rather than updating the password it just creates a new one with the same name, thus the new ID. 

I'm wondering if there is any hope that this script can be modified to avoid the change in Credential ID so it doesn't break the links in my jobs. 

Thanks,
Bill

MONIL PATEL

unread,
Oct 29, 2018, 3:10:52 PM10/29/18
to Jenkins Developers
Relace null with c.id as show below
new UsernamePasswordCredentialsImpl(c.scope, c.id, c.description, c.username, new_password)
Reply all
Reply to author
Forward
0 new messages