Last active
November 3, 2016 22:29
-
-
Save thomastaylor312/48d8904cc7c7aec10aaa0c75dc383b4a to your computer and use it in GitHub Desktop.
How to set credentials for Jenkins in Kubernetes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import jenkins.model.* | |
import hudson.model.* | |
import hudson.security.SecurityRealm | |
import org.jenkinsci.plugins.GithubSecurityRealm | |
import com.cloudbees.plugins.credentials.* | |
import com.cloudbees.plugins.credentials.common.* | |
import com.cloudbees.plugins.credentials.domains.* | |
import com.cloudbees.plugins.credentials.impl.* | |
import com.cloudbees.jenkins.plugins.sshcredentials.SSHUserPrivateKey | |
import com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey | |
import groovy.json.* | |
import javax.net.ssl.HostnameVerifier | |
import javax.net.ssl.HttpsURLConnection | |
import javax.net.ssl.SSLContext | |
import javax.net.ssl.TrustManager | |
import javax.net.ssl.X509TrustManager | |
// Bootstrapping to ignore SSL validation | |
def nullTrustManager = [ | |
checkClientTrusted: { chain, authType -> }, | |
checkServerTrusted: { chain, authType -> }, | |
getAcceptedIssuers: { null } | |
] | |
def nullHostnameVerifier = [ | |
verify: { hostname, session -> true } | |
] | |
SSLContext sc = SSLContext.getInstance("SSL") | |
sc.init(null, [nullTrustManager as X509TrustManager] as TrustManager[], null) | |
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()) | |
HttpsURLConnection.setDefaultHostnameVerifier(nullHostnameVerifier as HostnameVerifier) | |
// Get the environment | |
def env = System.getenv() | |
// Pick the right username for the server | |
def username = "my cool name" | |
// Get Domain and Credential store | |
domain = Domain.global() | |
store = Jenkins.instance.getExtensionList('com.cloudbees.plugins.credentials.SystemCredentialsProvider')[0].getStore() | |
// Get the token and namespace from where they are stored in the container | |
String kubeToken = new File('/var/run/secrets/kubernetes.io/serviceaccount/token').text | |
String namespace = new File('/var/run/secrets/kubernetes.io/serviceaccount/namespace').text | |
def target = sprintf('https://%1$s:%2$s/api/v1/namespaces/%3$s/secrets/password', [env['KUBERNETES_SERVICE_HOST'], env['KUBERNETES_PORT_443_TCP_PORT'], namespace]) | |
URL url = new URL(target); | |
URLConnection connection = url.openConnection(); | |
method = "GET" | |
connection.setDoOutput(true); | |
connection.setRequestMethod(method); | |
connection.addRequestProperty("Authorization", "Bearer " + kubeToken) | |
connection.connect(); | |
// An example of username/password | |
try { | |
InputStream response = connection.getInputStream(); | |
String content = new java.util.Scanner(response).useDelimiter("\\A").next(); | |
//Parse out password | |
def parsedContent = new JsonSlurper().parseText(content) | |
def password = new String(parsedContent['data']['password'].decodeBase64()) | |
usernameAndPassword = new UsernamePasswordCredentialsImpl( | |
CredentialsScope.GLOBAL, | |
"blahblah", "", | |
username, | |
password | |
) | |
store.addCredentials(domain, usernameAndPassword) | |
} catch(FileNotFoundException ex) { | |
println('ERROR: Unable to find password') | |
} | |
def sshTarget = sprintf('https://%1$s:%2$s/api/v1/namespaces/%3$s/secrets/key', [env['KUBERNETES_SERVICE_HOST'], env['KUBERNETES_PORT_443_TCP_PORT'], namespace]) | |
// Open a new connection to retrieve the key information | |
URL sshUrl = new URL(sshTarget); | |
URLConnection sshConnection = sshUrl.openConnection(); | |
sshConnection.setDoOutput(true); | |
sshConnection.setRequestMethod(method); | |
sshConnection.addRequestProperty("Authorization", "Bearer " + kubeToken) | |
sshConnection.connect(); | |
//How to set a private key credential | |
try { | |
InputStream sshResponse = sshConnection.getInputStream(); | |
String sshContent = new java.util.Scanner(sshResponse).useDelimiter("\\A").next(); | |
def parsedSSH = new JsonSlurper().parseText(sshContent); | |
// Read the JSON response | |
def key = new String(parsedSSH['data']['privatekey'].decodeBase64()); | |
def keyObj = new BasicSSHUserPrivateKey.DirectEntryPrivateKeySource(key) | |
keyAndPassphrase = new BasicSSHUserPrivateKey( | |
CredentialsScope.GLOBAL, | |
"915424c4-118f-4da4-aa81-ea6dad9ed5a1", | |
username, | |
keyObj, | |
"", "" | |
) | |
store.addCredentials(domain, keyAndPassphrase) | |
} catch(FileNotFoundException ex) { | |
println('ERROR: Unable to find key') | |
} | |
// Get the github oauth secret and password | |
def github_target = sprintf('https://%1$s:%2$s/api/v1/namespaces/%3$s/secrets/github-oauth', [env['KUBERNETES_SERVICE_HOST'], env['KUBERNETES_PORT_443_TCP_PORT'], namespace]) | |
URL github_url = new URL(github_target); | |
URLConnection connection2 = github_url.openConnection(); | |
connection2.setDoOutput(true); | |
connection2.setRequestMethod("GET"); | |
connection2.addRequestProperty("Authorization", "Bearer " + kubeToken) | |
connection2.connect(); | |
// How to set up github oauth | |
try { | |
InputStream github_response = connection2.getInputStream(); | |
String github_content = new java.util.Scanner(github_response).useDelimiter("\\A").next(); | |
//Parse out password | |
def githubParsed = new JsonSlurper().parseText(github_content) | |
def clientID = new String(githubParsed['data']['clientid'].decodeBase64()) | |
def clientSecret = new String(githubParsed['data']['clientsecret'].decodeBase64()) | |
// Configure the Github oauth | |
String githubWebUri = 'https://github.com' | |
String githubApiUri = 'https://api.github.com' | |
String oauthScopes = 'read:org,user:email' | |
SecurityRealm github_realm = new GithubSecurityRealm(githubWebUri, githubApiUri, clientID, clientSecret, oauthScopes) | |
//check for equality, no need to modify the runtime if no settings changed | |
if(!github_realm.equals(Jenkins.instance.getSecurityRealm())) { | |
Jenkins.instance.setSecurityRealm(github_realm) | |
Jenkins.instance.save() | |
} | |
} catch(FileNotFoundException ex) { | |
println('ERROR: Unable to find oauth credentials.') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment