Skip to content

Instantly share code, notes, and snippets.

@msheiny
Created May 30, 2018 11:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msheiny/7bb219c1cbfa963bc265814559543ae4 to your computer and use it in GitHub Desktop.
Save msheiny/7bb219c1cbfa963bc265814559543ae4 to your computer and use it in GitHub Desktop.
jenkins groovy init script for injecting google compute creds into credential store
import jenkins.model.*
import com.cloudbees.plugins.credentials.*
import org.apache.commons.fileupload.FileItem
import com.cloudbees.plugins.credentials.domains.*
import com.google.jenkins.plugins.credentials.oauth.JsonServiceAccountConfig
import com.google.jenkins.plugins.credentials.oauth.GoogleRobotPrivateKeyCredentials
import java.io.FileInputStream
domain = Domain.global()
store = Jenkins.instance.getExtensionList('com.cloudbees.plugins.credentials.SystemCredentialsProvider')[0].getStore()
def filey = new FileInputStream('/tmp/google-creds-on-jenkins-master.json')
fileItem = [ getSize: { return 1L }, getInputStream: { return filey } ] as FileItem
def ServiceAccount = new JsonServiceAccountConfig(fileItem, null)
def GoogleAccount = new GoogleRobotPrivateKeyCredentials("project-id", ServiceAccount, null)
store.addCredentials(domain, GoogleAccount)
@gvirtuoso
Copy link

gvirtuoso commented Jun 14, 2019

Hi @msheiny,

Your code didn't work for me, so I did some improvements now it's working. (Jun/2019).
Anyway, thank you so much. Your code was the inspiration. ;-)

import org.apache.commons.io.FileUtils
import org.apache.commons.fileupload.FileItem
import com.google.jenkins.plugins.credentials.oauth.JsonServiceAccountConfig
import com.google.jenkins.plugins.credentials.oauth.GoogleRobotPrivateKeyCredentials

def jenkinsInstance = Jenkins.getInstance()

// Google Credential
def googleCredentialId = "my-credential-id"
def googleCredentialFile = new File("/path/to/my/json/file.json")
def googleCredentialFileInputStream = new FileInputStream(googleCredentialFile)
def googleCredentialFileItem = [ getName: { return googleCredentialFile.getName() }, getSize: { return 1L }, getInputStream: { return googleCredentialFileInputStream }, get: { return FileUtils.readFileToByteArray(googleCredentialFile) } ] as FileItem
def googleJsonServiceAccountConfig = new JsonServiceAccountConfig(googleCredentialFileItem, null)
def googleCredential = new GoogleRobotPrivateKeyCredentials(googleCredentialId, googleJsonServiceAccountConfig, null)

// Saving
def domain = Domain.global()
def store = jenkinsInstance.getExtensionList('com.cloudbees.plugins.credentials.SystemCredentialsProvider')[0].getStore()
store.addCredentials(domain, googleCredential)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment