Creating credentials using Groovy

Article ID:217708168
1 minute readKnowledge base

Issue

Could I create a credential and append it to a folder through a Groovy script?

Environment

  • CloudBees Jenkins Enterprise > 1.609.1.1

  • Jenkins LTS > 1.609.1

  • Jenkins > 1.600

Resolution

It is possible to manipulate credentials using a Groovy script. You can create or edit credentials and add them to Jenkins’s global scope or add them to a domain in a folder. Here are two examples of how to do it.

Example Groovy script to add credentials to Jenkins.

import com.cloudbees.plugins.credentials.impl.*
import com.cloudbees.plugins.credentials.*
import com.cloudbees.plugins.credentials.domains.*

String keyfile = "/tmp/key"

Credentials c = (Credentials) new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL,java.util.UUID.randomUUID().toString(), "description", "user", "password")

def ksm1 = new CertificateCredentialsImpl.UploadedKeyStoreSource(keyfile)
Credentials ck1 = new CertificateCredentialsImpl(CredentialsScope.GLOBAL,java.util.UUID.randomUUID().toString(), "description", "password", ksm1)

SystemCredentialsProvider.getInstance().getStore().addCredentials(Domain.global(), c)
SystemCredentialsProvider.getInstance().getStore().addCredentials(Domain.global(), ck1)

Example Groovy script to add credentials to Jenkins’s folder into global domain.

import jenkins.model.*
import com.cloudbees.hudson.plugins.folder.*
import com.cloudbees.hudson.plugins.folder.properties.*
import com.cloudbees.hudson.plugins.folder.properties.FolderCredentialsProvider.FolderCredentialsProperty
import com.cloudbees.plugins.credentials.impl.*
import com.cloudbees.plugins.credentials.*
import com.cloudbees.plugins.credentials.domains.*

jenkins = Jenkins.instance

String id = java.util.UUID.randomUUID().toString()
Credentials c = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, id, "description:"+id, "user", "password")

for (folder in jenkins.getAllItems(Folder.class)) {
  if(folder.name.equals('FolderName')){
	AbstractFolder<?> folderAbs = AbstractFolder.class.cast(folder)
    FolderCredentialsProperty property = folderAbs.getProperties().get(FolderCredentialsProperty.class)
    property.getStore().addCredentials(Domain.global(), c)
    println property.getCredentials().toString()
  }
}

Example Groovy script to add SSH Username and Private Key credentials to Jenkins.

import com.cloudbees.plugins.credentials.impl.*
import com.cloudbees.plugins.credentials.*
import com.cloudbees.plugins.credentials.domains.*
import com.cloudbees.jenkins.plugins.sshcredentials.impl.*

def source = new BasicSSHUserPrivateKey.DirectEntryPrivateKeySource("key")
def ck1 = new BasicSSHUserPrivateKey(CredentialsScope.GLOBAL,java.util.UUID.randomUUID().toString(), "username", source, "passphrase", "description")

SystemCredentialsProvider.getInstance().getStore().addCredentials(Domain.global(), ck1)

Tested on

The latest update of this article has been tested with: