pers
pers

Reputation: 195

Update aws credential in jenkins file with a groovy script

In my process regularly I get temporary AWS cred and in my Jenkins file I need to update a specific Jenkins Aws crednetial. How can I update it? The reason that I need is that Jenkins docker method withRegistry requires credential id and I have to update this credential whenever I get new AWS key to be able to use it.

Upvotes: 3

Views: 2198

Answers (1)

pers
pers

Reputation: 195

After several try and error I found this:

import jenkins.model.*
import com.cloudbees.plugins.credentials.*
import com.cloudbees.plugins.credentials.impl.*
import com.cloudbees.plugins.credentials.domains.*
import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey
import com.cloudbees.jenkins.plugins.awscredentials.AWSCredentialsImpl
import org.jenkinsci.plugins.plaincredentials.StringCredentials
   def changePassword = { id,accessKey, secKey ->
def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
    com.cloudbees.jenkins.plugins.awscredentials.AWSCredentialsImpl.class,
    Jenkins.instance
)
def c = creds.findResult { it.id == id ? it : null }
if ( c ) {
    println "found credential ${c.id} for accessKey ${c.accessKey}"

    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 AWSCredentialsImpl(c.scope, id, accessKey, secKey,c.description)
        )

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

Upvotes: 4

Related Questions