Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ivan-pinatti/830ec918781060df03b12efd4a14096e to your computer and use it in GitHub Desktop.
Save ivan-pinatti/830ec918781060df03b12efd4a14096e to your computer and use it in GitHub Desktop.
Jenkins - Add Username with password credential via groovy script - #jenkins #groovy #username #password #credential #usernameWithPassword
#!groovy
// imports
import com.cloudbees.plugins.credentials.*
import com.cloudbees.plugins.credentials.domains.Domain
import com.cloudbees.plugins.credentials.impl.*
import hudson.util.Secret
import jenkins.model.Jenkins
// parameters
def jenkinsKeyUsernameWithPasswordParameters = [
description: 'Description here',
id: 'key-id-here',
secret: '12345678901234567890',
userName: 'your-username-here'
]
// 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 Bitbucket secret
def jenkinsKeyUsernameWithPassword = new UsernamePasswordCredentialsImpl(
CredentialsScope.GLOBAL,
jenkinsKeyUsernameWithPasswordParameters.id,
jenkinsKeyUsernameWithPasswordParameters.description,
jenkinsKeyUsernameWithPasswordParameters.userName,
jenkinsKeyUsernameWithPasswordParameters.secret
)
// add credential to store
store.addCredentials(domain, jenkinsKeyUsernameWithPassword)
// save to disk
jenkins.save()
@manastri
Copy link

worked like charm

@anandasubedi
Copy link

it worked! Would be great if we could also add "ssh username with the private key " option

@ivan-pinatti
Copy link
Author

it worked! Would be great if we could also add "ssh username with the private key " option

Please check this other one @anandasubedi , I believe this is what are you referring to;

https://gist.github.com/ivan-pinatti/de063b610d1bdf2da229c7874968f4d9

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