Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save chaitanyakommoju/211c16e17e1e095587424e5d4a47aca1 to your computer and use it in GitHub Desktop.
Save chaitanyakommoju/211c16e17e1e095587424e5d4a47aca1 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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment