Hi everyone,
I've run into an issue with the Jenkins plugin I'm working on and I could use some help. The plugin uses a REST API with an API Token, and the API Token is stored in the Credentials plugin as a 'Secret Text' type.
The plugin works fine when run from the master Jenkins instance, but if it's run on a slave node it crashes when trying to access the Credentials.
Below is the code we are using to access the credentials:
public String getCredentialWithId(String credentialId) {
List<StringCredentials> stringCredentials = fetchStringCredentials();
StringCredentials credential = CredentialsMatchers.firstOrNull(stringCredentials,
CredentialsMatchers.withId(credentialId));
String secret = null;
if (credential != null) {
secret = credential.getSecret().getPlainText();
}
return secret;
}
private List<StringCredentials> fetchStringCredentials() {
return CredentialsProvider.lookupCredentials(
StringCredentials.class,
Jenkins.getInstance(),
ACL.SYSTEM,
Collections.<DomainRequirement>emptyList()
);
}
The problem exists with 'Jenkins.getInstance()' in 'fetchStringCredentials()'. This will return 'null' if it's not run on the master Jenkins instance. Is there a way to access credentials stored in the Credentials
plugin when running on a slave node?
I've tried using the 'CredentialsProvider.findCredentialById()' function to get the Credential in the below example.
public String getCredentialsWithIdFromRun(String credentialsId, Run run) {
if (StringUtils.isBlank(credentialsId)) {
return null;
}
StringCredentials result = CredentialsProvider.findCredentialById(
credentialsId,
StringCredentials.class,
run,
Collections.<DomainRequirement>emptyList());
return result.getSecret().getPlainText();
}
However, this gives me the wrong value for the Credential ID (not null).
Any advice would be appreciated.
Thanks,
Andrew