I am working on an integration with Jenkins and AWS Secrets Manager and the plugin does not support arbitrary key-value pair. What I am after is a solution that can parse some data (i.e. the AWS credential) and return a different credential that has the protection of masking that Jenkins provides. In my specific use-case I am attempting to convert a multi-field postgresql secret into a connection string.
This is what I am attempting to do
import static com.cloudbees.plugins.credentials.CredentialsScope.GLOBAL
import static com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials;
import groovy.json.JsonSlurper;
import com.cloudbees.plugins.credentials.*;
import org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl;
import hudson.util.Secret
def call(String dbName) {
def env = System.getenv("ENV") ?: "dev";
def credID = "${env}/${dbName}/postgresql";
def creds = CredentialsMatchers.firstOrNull(
lookupCredentials(Credentials.class, Jenkins.get(), null, null),
CredentialsMatchers.withId(credID));
if (creds == null) {
throw new IllegalStateException("No credentials found for database: " + dbName);
}
def jsonSlurper = new JsonSlurper();
def c = jsonSlurper.parseText(creds.getSecret().toString());
def secret = "${c.engine}://${c.username}:${c.password}@${c.host}:${c.port}/${c.dbname}";
return new StringCredentialsImpl(GLOBAL, "${dbName}-postgresql", "", Secret.fromString(secret));
}
The code runs fine but unfortunately when I try to consume it in a Jenkins pipeline I am not getting what I expected.
Expected Behavior:
Calling the custom function would behave the same as the credentials
function in a Jenkins pipeline. For example, DATABASE_URL = credentials('database')
results in a variable that can be used as a string in the pipeline and is masked by "*******" if it is written to the console or a file.
Actual Behavior:
Calling DATABASE_URL = customCreds('database')
results in the DB
variable being assigned the object name itself.
DATABASE_URL=org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl@81bf833e
I am definitely a little out of my element here so any help would be greatly appreciated. As it stands I am getting to the point of abandoning trying to create a "credential" in favor of just returning the string and being careful in my pipelines to ensure the credentials are not exposed.