List all credentials from jenkins

2024-02-22 / DevOps Jenkins

This post is mainly to help your list all credentials from Jenkins.

Run the following code in Dashboard -> Manage Jenkins -> Tools and Actions -> Script Console

import com.cloudbees.plugins.credentials.Credentials
import com.cloudbees.plugins.credentials.CredentialsProvider

CredentialsProvider.lookupCredentials(Credentials.class, Jenkins.instance, null, null).each { c ->
    def className = c.properties.class.toString()
    def p = c.properties
    println("ID: ${c.id}")
    println("Scope: ${c.scope}")
    println("Description: ${c.description}")
    println("Type: ${className.substring(className.lastIndexOf('.') + 1)}")
    switch (c.properties.class.toString()) {
        case 'class com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl':
            println("Username: ${p.username}")
            println("Password: ${p.password}")
            break
        case 'class com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey':
            println("Username: ${p.username}")
            println("Private Key: |")
            println("${p.privateKey}")
            break
        case 'class org.jenkinsci.plugins.plaincredentials.impl.FileCredentialsImpl':
            println("Filename: ${p.fileName}")
            println("File Content: |")
            println("${new String(c.getSecretBytes().getPlainData())}")
            break
        case 'class org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl':
            println("Secret: ${p.secret}")
            break
        default:
            println("WARN: unknown credential type")
            println("credential properties: ${p.toString()}")
    }
    println("------------------------------------------------------------------------------")
}

Or use the more tidy code

com.cloudbees.plugins.credentials.SystemCredentialsProvider.getInstance().getCredentials().forEach{
  it.properties.each { prop, val ->
    println(prop + " = " + val)
  }
  println("----------------------------------------------------")
}