Fetch the domain for each credential returned in a job template.

Article ID:218233428
1 minute readKnowledge base

Issue

  • Fetch the domain for each credential retrieved in a template job using groovy script

When Job XXX is instated it should use credentials 2 as it is searching for credentials 'AAA'

Environment

  • CloudBees Jenkins Enterprise

Resolution

Credentials do not know what domain they are stored in. Retrieving a list of domains is not very straightforward, as each CredentialsProvider implements the storage and retrieval of credentials in different ways. But if you for example know that a credential is stored in a folder you can get the list of domains in that folder via the 'FolderCredentialsProperty' and then in turn get the credentials in that domain. Something like the following in a groovy script:

def property = folder.getProperties().get(FolderCredentialsProvider.FolderCredentialsProperty.class) property.getDomainCredentials().each { println it.domain.name //do something with it.credentials }
  • Additional background/use case: Customer is using script in attempt to find the credentials that match a name when reverse traversing up the folder structure…​ Folder A Credential name: AAA, id 1 Folder B Credential AAA, id 2 Folder C Job XXXXX

That script would look something like this:

import groovy.json.* def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials( com.cloudbees.plugins.credentials.common.StandardCredentials.class, Jenkins.getInstance().getItemByFullName("WI/GEI-OPS/DEV/SD000142/TR101783") , null, null ); class FileCredentials { String id String description String filename } def filecreds = new ArrayList<FileCredentials> () for (c in creds) { if (c.class.canonicalName == 'org.jenkinsci.plugins.plaincredentials.impl.FileCredentialsImpl') { def fileCred = new FileCredentials(id : c.id, description :c.description, filename: "" ) filecreds << fileCred } } def json2 = new JsonBuilder() json2.state { credentials filecreds } print json2 //print JsonOutput.toJson (filecreds)