Skip to content

Instantly share code, notes, and snippets.

@ojacques
Created July 22, 2021 11:33
Show Gist options
  • Save ojacques/56a62e7607482ba3761751a9380db1b3 to your computer and use it in GitHub Desktop.
Save ojacques/56a62e7607482ba3761751a9380db1b3 to your computer and use it in GitHub Desktop.
Jenkins useful groovy scripts

https://the-jenkins/script

Delete offline nodes

for (aSlave in hudson.model.Hudson.instance.slaves) {
    if (aSlave.getComputer().isOffline()) {
        aSlave.getComputer().setTemporarilyOffline(true,null);
        aSlave.getComputer().doDoDelete();
    }
}

Get creds

def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
        com.cloudbees.plugins.credentials.Credentials.class,
        Jenkins.getInstance().getItemByFullName("githuborg/githubrepo/"),
        null,
        null
);

def indent = { String text, int indentationCount ->
  def replacement = "\t" * indentationCount
  text.replaceAll("(?m)^", replacement)
}

println("Found " + creds.size() + " credentials:");
creds.each { cred ->
      cred.properties.each { prop, val ->
        println indent("$prop = \"$val\"", 2)
      }
      println indent("-----------------------", 2)
    }

Get creds for all orgs

Or for all orgs:

import com.cloudbees.plugins.credentials.CredentialsProvider
import com.cloudbees.plugins.credentials.Credentials
import com.cloudbees.plugins.credentials.domains.Domain
import jenkins.model.Jenkins
def indent = { String text, int indentationCount ->
  def replacement = "\t" * indentationCount
  text.replaceAll("(?m)^", replacement)
}

Jenkins.get().allItems().collectMany{ CredentialsProvider.lookupStores(it).toList()}.unique().forEach { store ->
  Map<Domain, List<Credentials>> domainCreds = [:]
  store.domains.each { domainCreds.put(it, store.getCredentials(it))}
  if (domainCreds.collectMany{ it.value}.empty) {
    return
  }
  def shortenedClassName = store.getClass().name.substring(store.getClass().name.lastIndexOf(".") + 1)
  println "Credentials for store context: ${store.contextDisplayName}, of type $shortenedClassName"
  domainCreds.forEach { domain , creds ->
    println indent("Domain: ${domain.name}", 1)
    creds.each { cred ->
      cred.properties.each { prop, val ->
        println indent("$prop = \"$val\"", 2)
      }
      println indent("-----------------------", 2)
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment