How do I list which Jenkins credentials used per pipeline in the script console?

16 views Asked by At

Inheriting a Legacy Jenkins is always a challenge, people long gone, with barely any documentation. Luckily we can automate some processes and ask our good old friend Jenkins about which credentials are being used on which pipeline, In my case the objective is to cycle the credential sets and disable those out of use and regain control.

1

There are 1 answers

0
ximbal On

here's what I've used:

import jenkins.model.Jenkins
import hudson.model.Job
import com.cloudbees.hudson.plugins.folder.Folder
import com.cloudbees.plugins.credentials.CredentialsProvider
import com.cloudbees.plugins.credentials.Credentials
import java.nio.charset.StandardCharsets

// Define a method to fetch all credentials
def getCreds() {
    return CredentialsProvider.lookupCredentials(Credentials.class)
}

// Function to print credential details in CSV format
def printCredentialDetailsInCsvFormat(job, c) {
    def description = c.description ? c.description : ""
    println("\"${job.fullName}\",\"${c.id}\",\"${description}\"")
}

// Utility function to search for credentials in job configurations and print in CSV format
def searchCredentialsInConfig(job, creds) {
    def jobConfig = job.getConfigFile().asString()
    // Iterate over all credentials to find if they are referenced in this job config
    creds.each { c ->
        if (jobConfig.contains(c.id)) {
            printCredentialDetailsInCsvFormat(job, c)
        }
    }
}

// Recursive function to process all items including those in folders, now accepts creds as an argument
def processItem(item, creds) {
    if (item instanceof Folder) {
        item.getItems().each { subItem ->
            processItem(subItem, creds)
        }
    } else if (item instanceof Job) {
        searchCredentialsInConfig(item, creds)
    }
}

// Print CSV header
println("\"Pipeline Name\",\"Credential ID\",\"Description\"")

// Get all credentials before starting the item processing
def creds = getCreds()

// Start processing all items from Jenkins root, passing creds along
Jenkins.instance.items.each { item ->
    processItem(item, creds)
}

the output being:

"Pipeline Name","Credential ID","Description"
"Some credential","some UUID","Some Description"
...

Please feel free to improve it.