Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save ivan-pinatti/de063b610d1bdf2da229c7874968f4d9 to your computer and use it in GitHub Desktop.
Save ivan-pinatti/de063b610d1bdf2da229c7874968f4d9 to your computer and use it in GitHub Desktop.
Jenkins - Add SSH keypair with password credential via groovy script - #jenkins #groovy #ssh #credential
#!groovy
// imports
import com.cloudbees.jenkins.plugins.sshcredentials.impl.*
import com.cloudbees.plugins.credentials.*
import com.cloudbees.plugins.credentials.common.*
import com.cloudbees.plugins.credentials.domains.Domain
import com.cloudbees.plugins.credentials.impl.*
import hudson.util.Secret
import java.nio.file.Files
import jenkins.model.Jenkins
import net.sf.json.JSONObject
import org.jenkinsci.plugins.plaincredentials.impl.*
// parameters
def jenkinsMasterKeyParameters = [
description: 'Jenkins Master SSH Key',
id: 'jenkins-master-key',
secret: 'PleaseUseOnePasswordStrongEnough!',
userName: 'my-jenkins@my-company.com',
key: new BasicSSHUserPrivateKey.DirectEntryPrivateKeySource('''-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQCNEn6kcPiFHyJo3cO+KiUZ21kG2ePPnYq0DnX+ZACllJUHA6Fn
gbuRK48UVGpcuZ2OPHlDb+fYXBZu5MVewsbqgOO1B0eDX5GV4Fy7qJx8d1BFyvQA
KpCc9c/DDUIG5yFhPCGpLCSit4CA8soVH7NeCOk1lzU18mMlWaaMT8HMfQIDAQAB
AoGAOiUZVaXKiPPgNuDQwRyV1iZ2d0BviS8h8DzVnViSe6zWD+ILMKJkMN2HR5XT
kQxgSDPct1L0eFTcWjCouPoHChhOXCWMOxHxXv+r5Gbt6kRmRr4DOGsz2a2vZwEJ
MI4c67olZsLtLAeEG/y9dHP+i7YrGkoMXM2aZZkvANWypvECQQDsnWT1VS+TDFGB
UuDQQuCFkF/g3nW4wqKML/hxaoFOJzKYLTf7ja2ovp56Clq0w/VzQXaiKnapXSjN
gZoBH5qTAkEAmKFAmqSlUhukuerEyw9VfMHNO5uj28u7skkf8BynJ1mLQtvoCBp5
RyotXzjzOszWlwf+JAYrzOD0+DenizeWrwJBAN7lMlruIX/rpcgm88McjPclVzy1
M76WE5vuAKOOyjp+MGoshsVA5OvGjfG3WVVaGBm3/HKtf9Tx/mMBiLswM2MCQA0H
vzc0lTSUTZTduR1I2tiCxx2upOeP1h9bZNGf8JlIaL41ffKrJ+1uaV82wnUjpbJR
KV4z9KtSDTffsHsPLNsCQQCvx7SPjGCrZwqeZBM6QBYi3r6q0TXO1avgGhAx6N9b
YE4W1Ve8Pwkl0DCb9IaWu8DVthllS6tBSL+KrrfOZIvO
-----END RSA PRIVATE KEY-----''')
]
// get Jenkins instance
Jenkins jenkins = Jenkins.getInstance()
// get credentials domain
def domain = Domain.global()
// get credentials store
def store = jenkins.getExtensionList('com.cloudbees.plugins.credentials.SystemCredentialsProvider')[0].getStore()
// define private key
def privateKey = new BasicSSHUserPrivateKey(
CredentialsScope.GLOBAL,
jenkinsMasterKeyParameters.id,
jenkinsMasterKeyParameters.userName,
jenkinsMasterKeyParameters.key,
jenkinsMasterKeyParameters.secret,
jenkinsMasterKeyParameters.description
)
// add credential to store
store.addCredentials(domain, privateKey)
// save to disk
jenkins.save()
@psahindrakar
Copy link

Thank you for the scripts you have shared. Really appreciated. It has helped set up Jenkins on docker with pre-configured plugins, jobs, and credentials.

@jeyrichman
Copy link

Thank you, it helped a lot!

@AtibJunaid
Copy link

Can you please tell me how can I pass the key as a variable?
As it's a private key , i couldn't used directly as in code.
Please any one

@ivan-pinatti
Copy link
Author

Hi @AtibJunaid,

Do you mean environment variables or arguments? If it is the first, you can check it on this thead; https://stackoverflow.com/questions/40215394/how-to-get-environment-variable-in-jenkins-groovy-script-console

@AtibJunaid
Copy link

Hello @ivan-pinatti
Thank you for your response.
Iam using shell command to create public key and private key.
And I am adding public key to GitHub using api.
And I want to create a Jenkins credentials with private key.
Here in above code the private key is added in the script itself.
Due to security I can't add the key directly here in the script.
So I wanted to know how can I add private key .
In pipeline iam using
Stage(add private key){
Code = load 'ssh.groovy'

@ivan-pinatti
Copy link
Author

You can inject through an environment variable and then use it. If I am understanding what you are trying to achieve @AtibJunaid .

@CondehA
Copy link

CondehA commented Jun 22, 2022

Do you anything where we can scope the credential to Folder level.

@ivan-pinatti
Copy link
Author

Do you anything where we can scope the credential to Folder level.

Sorry, I didn't understand your question @CondehA . Could you please elaborate more?

@CondehA
Copy link

CondehA commented Jun 29, 2022

in this code we are making global credentials , I want to make it scoped to folder level so only folder jobs can access these credentials.
image
image

@ivan-pinatti
Copy link
Author

@CondehA, I never done on the folder level, but it mustn't be that hard.

Probably some adjustments and testing on this code you can achieve it.

Try changing line 42 where the domain is set, and also line 49.

If it doesn't work, try exploring reading the class documentation here.

I hope it helps.

Cheers!

@AtibJunaid
Copy link

AtibJunaid commented Jun 21, 2023

Hello @ivan-pinatti
Thank You for the script, it really works.
I also used updateCredentials(domain, currentkey, newkey)
so it also works.

@ivan-pinatti
Copy link
Author

Hi @AtibJunaid,

That's good to hear.
Consider sharing the update script in your Gist and putting a link here so others can benefit from it as well. 😉

In addition, consider buying a simple coffee as I do these on my free time; https://www.buymeacoffee.com/ivan.pinatti

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