Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save xiaojueguan/32d33b8b161764c27e231320e5dcce33 to your computer and use it in GitHub Desktop.
Save xiaojueguan/32d33b8b161764c27e231320e5dcce33 to your computer and use it in GitHub Desktop.
jenkins script create credentials with json string
import com.cloudbees.plugins.credentials.impl.*
import com.cloudbees.plugins.credentials.*
import com.cloudbees.plugins.credentials.domains.*
import com.cloudbees.jenkins.plugins.sshcredentials.impl.*
import groovy.json.JsonSlurper
def createCredentialsByJsonStr(credsJsonStr) {
jsonSlurper = new JsonSlurper()
creds = jsonSlurper.parseText(credsJsonStr)
creds.each{cred->
Credentials c
attrs = cred['attrs']
if (cred['type'] == 'UsernamePasswordCredentialsImpl') {
c = (Credentials) new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, attrs['id'], attrs['desc'], attrs['username'], attrs['password']['plainText'])
} else if (cred['type'] == 'BasicSSHUserPrivateKey') {
BasicSSHUserPrivateKey.DirectEntryPrivateKeySource storeSource = new BasicSSHUserPrivateKey.DirectEntryPrivateKeySource(attrs['privateKey'])
c = new BasicSSHUserPrivateKey(CredentialsScope.GLOBAL, attrs['id'], attrs['username'], storeSource, attrs['passphrase'], attrs['desc'])
}
SystemCredentialsProvider.getInstance().getStore().addCredentials(Domain.global(), c)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment