Skip to content

Instantly share code, notes, and snippets.

@hayderimran7
Last active June 15, 2018 10:40
Show Gist options
  • Save hayderimran7/59305ef647e971e5114e4d5271dd8928 to your computer and use it in GitHub Desktop.
Save hayderimran7/59305ef647e971e5114e4d5271dd8928 to your computer and use it in GitHub Desktop.
Create a new jenkins global credential from a key source on jenkins master(groovy script)

Create a New jenkins global credential from a key stored on jenkins master

This script helps create a global credential in jenkins from a key source that is located in jenkins master.
You can change the name of key to whatever key exists on master.
Run this script either:

i) Jenkins-> manage Jenkins -> script console

ii) add to init.groovy to make it run during jenkins start

alright heres the script(here i assume my key already exists on master as /root/.ssh/id_rsa :

import com.cloudbees.plugins.credentials.*
import com.cloudbees.plugins.credentials.common.*
import com.cloudbees.plugins.credentials.domains.*
import com.cloudbees.jenkins.plugins.sshcredentials.impl.*
  
  String keyfile = "/root/.ssh/id_rsa"
global_domain = Domain.global()
credentials_store =
Jenkins.instance.getExtensionList(
'com.cloudbees.plugins.credentials.SystemCredentialsProvider'
)[0].getStore()
credentials = new BasicSSHUserPrivateKey(
CredentialsScope.GLOBAL,
null,
"root",
 new BasicSSHUserPrivateKey.FileOnMasterPrivateKeySource(keyfile),
"",
"")
credentials_store.addCredentials(global_domain, credentials)

After you run through script console, the result should look like:

Result: true

cheers :)

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