Michael
Michael

Reputation: 2683

How to add a secret using a post-initialization script

I need a secret text to be configured in a post-initialization script in my Jenkins. Until now I only found code to configure username/password credentials, but I just don't know the right classes to use for a secret text. My current approach is:

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

Credentials c = (Credentials) new WhateverClassSecretText(
    CredentialsScope.GLOBAL,
    "my-credential-id",
    "Secret Text for something", 
    "S3cr3t") // TODO find right class here!

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

Upvotes: 0

Views: 1210

Answers (1)

Michael
Michael

Reputation: 2683

I found a way to do it but I'm still curious if anyone has a better solution.

The class I was looking for is org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl, which actually takes a hudson.util.Secret as the secret string. Here is the code (testable in Jenkins Script Console):

import static com.cloudbees.plugins.credentials.CredentialsScope.GLOBAL

import com.cloudbees.plugins.credentials.domains.Domain
import com.cloudbees.plugins.credentials.SystemCredentialsProvider
import hudson.util.Secret
import org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl

StringCredentialsImpl credentials = new StringCredentialsImpl(
    GLOBAL,
    "my-credential-id",
    "Secret Text for something",
    Secret.fromString("S3cr3t"))

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

Upvotes: 1

Related Questions