简体   繁体   中英

How to update credentials of specific folder in Jenkins using Groovy script?

I want to update a credentials object of an existing folder. How can I do that using groovy?
Here is what I have so far:

import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials;
import com.cloudbees.hudson.plugins.folder.Folder
import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl

// Init
String user_name = "my_user_name"
String user_pass = "my_new_pass"
String folderName = "Projects"
Folder targetFolder = null

// Get folder:
def allJenkinsItems = Jenkins.getInstance().getItems();
for (currentJenkinsItem in allJenkinsItems)
{
    if(!(currentJenkinsItem instanceof Folder)) {continue}

    if(((Folder)currentJenkinsItem).getFullName().equals(folderName))
    {
        targetFolder = (Folder)currentJenkinsItem;
    }
}
if (targetFolder == null) {println "Failed to find folder: folderName"; return}

// Get target credentials of that folder:
def credsList = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
    com.cloudbees.plugins.credentials.common.StandardUsernameCredentials.class,
    targetFolder,
    null,
    null
);

// Get target creds out of the list - will get the first one it encounters:
def targetCreds = credsList.findResult { it.username == user_name ? it : null }
if (targetCreds == null) {println "Failed to find username: $user_name under credentials of folder: $folderName"; return}

// Gets store - how to get the folder's store??
def credentials_store = Jenkins.instance.getExtensionList(
    'com.cloudbees.plugins.credentials.SystemCredentialsProvider'
)[0].getStore()

// Try to update the creds of the folder. 
//   **updateResult is always 'false' here**
def updateResult = credentials_store.updateCredentials(
    com.cloudbees.plugins.credentials.domains.Domain.global(), 
    targetCreds, 
    new UsernamePasswordCredentialsImpl(targetCreds.scope, targetCreds.id, targetCreds.description, targetCreds.username, user_pass)
)

if (updateResult) {
    println "Success changing password for ${user_name}" 
} else {
    println "Failed changing password for ${user_name}"
}

But when I am trying to update - I get a updateResult == false.
How can I update the credentials after they are found?

Found it myself:

/*
* Configures single (username & password) credentials for a folder in global domain
*  if already exists a credentials with defined username - it will update it
*  if more than one exists - the first one it encounters will be updated
*/

import java.util.logging.Logger
import jenkins.model.*
import com.cloudbees.hudson.plugins.folder.*;
import com.cloudbees.hudson.plugins.folder.properties.*;
import com.cloudbees.hudson.plugins.folder.properties.FolderCredentialsProvider.FolderCredentialsProperty;
import com.cloudbees.plugins.credentials.impl.*;
import com.cloudbees.plugins.credentials.*;
import com.cloudbees.plugins.credentials.domains.*;

// Init
def logger = Logger.getLogger("")
jenkins = Jenkins.instance

String user_name = "my_user_name"
String user_pass = "my_new_pass"
String description = "my desc"
String folderName = "Projects"


String id = java.util.UUID.randomUUID().toString()
Credentials c = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, id, "description: "+id, user_name, user_pass)

logger.info("Configuring domain credentials for folder: $folderName")
for (folder in jenkins.getAllItems(Folder.class)) {
    if(folder.name.equals(folderName)) {
        AbstractFolder<?> folderAbs = AbstractFolder.class.cast(folder)
        FolderCredentialsProperty property = folderAbs.getProperties().get(FolderCredentialsProperty.class)

        // If not defined FolderCredentialsProperty yet - define and finish
        if(property == null) {
            logger.info("Initializing folder credentials store and add credentials in global store")
            property = new FolderCredentialsProperty([c])
            folderAbs.addProperty(property)
            jenkins.save()
            return
        }

        // Check for existing credentials - and update their password & description
        //   will update the first credentials it encounters
        def credentials_store = property.getStore()
        List<com.cloudbees.plugins.credentials.Credentials> folderCredentialsList = property.getCredentials()
        for (creds in folderCredentialsList) {
            logger.info("Checking existing credentials of folder: $folderName for user: $user_name")
            if (creds.username.equals(user_name)) {
                // Found username - updating it
                //  Try to update the creds of the folder:
                def updateResult = credentials_store.updateCredentials(
                        com.cloudbees.plugins.credentials.domains.Domain.global(),
                        creds,
                        new UsernamePasswordCredentialsImpl(creds.scope, creds.id, description, creds.username, user_pass)
                )
                if (updateResult) {
                    println "Update successful"
                } else {
                    println "Update failed"
                }
                jenkins.save()
                return
            }

        }

        logger.info("Didn't find credntials with username: $user_name - adding new one")

        // If got here - then:
        //  1. There is already a FolderCredentials property defined for folder: folderName
        //  2. didn't find any credentials(of username & password type) with username == user_name
        // so just add the new credentials
        property.getStore().addCredentials(Domain.global(), c)
        jenkins.save()
        return
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM