Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save JD10NN3/c61bea393834510e875b28bcbce56d1a to your computer and use it in GitHub Desktop.
Save JD10NN3/c61bea393834510e875b28bcbce56d1a to your computer and use it in GitHub Desktop.
Simple Groovy script to import Openshift Secrets with Jenkins
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import com.cloudbees.plugins.credentials.impl.*;
import com.cloudbees.plugins.credentials.*;
import com.cloudbees.plugins.credentials.domains.*;
import org.jenkinsci.plugins.plaincredentials.*
import org.jenkinsci.plugins.plaincredentials.impl.*
import hudson.util.Secret
def jsonSlurper = new JsonSlurper()
def sout = new StringBuilder(), serr = new StringBuilder()
def proc = 'oc get secrets --selector=jenkins=true -o json --no-headers=true'.execute()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
def mapping = jsonSlurper.parseText(sout.toString())
for(item in mapping.items) {
Credentials credential
// determine the type of credential to create
if(item.data.username && item.data.password) { /* username and password type */
def username = new String(item.data.username.decodeBase64())
def password = new String(item.data.password.decodeBase64())
def description = item.metadata.labels['jenkins-description']
credential = (Credentials) new UsernamePasswordCredentialsImpl(
CredentialsScope.GLOBAL, // Scope
item.metadata.name, // id
description, // description
username, // username
password // password
)
} else if(item.data.token) { /* token type */
def token = new String(item.data.token.decodeBase64())
def description = item.metadata.labels['jenkins-description']
// Secret text
credential = (Credentials) new StringCredentialsImpl(
CredentialsScope.GLOBAL, // Scope
item.metadata.name, // id
description, // description
Secret.fromString(token) // secret
)
} else {
// No type match found...
return;
}
// delete and re/create credential
SystemCredentialsProvider.getInstance().getStore().removeCredentials(Domain.global(), credential)
SystemCredentialsProvider.getInstance().getStore().addCredentials(Domain.global(), credential)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment