How to set Jenkins auth2 credential from String?

Viewed 61

I'm using the Jenkins parametrised remote trigger plugin to call Jenkins server (A) from our Jenkins server (B). It's been working successfully using the Jenkins credential manager, but I'm now wishing to fetch it at run time and then pass in that fetched credential directly as a string, rather than have it stored in Jenkins.

Essentially I'm trying to get a String into an auth2 object to use in my remote trigger.

Existing code:

triggerRemoteJob job: "${REMOTE_JOB}",
        parameters: "REDACTED",
        auth: CredentialsAuth(credentials: "cred-id")

What I'm working towards:

def fetchedCred = getFromThirdPartyResource()
triggerRemoteJob job: "${REMOTE_JOB}",
        parameters: "REDACTED",
        auth: CredFromString(fetchedCred)
1 Answers

The solution really depends on the type of Authentication method you intend to use. Since you are using CredentialsAuth I assume you plan on using Basic Auth. In Basic Auth you will be passing the Authorization header like below

Authorization: Basic username:password (username:password will be base64 encoded)

So in order to get around your issue, you can use TokenAuth instead of CredentialsAuth. If you look at the code here TokenAuth is also generating a Basic Auth header with the provided apiToken and userName. Hence you can use something like the below.

pipeline {
    agent any
    stages {
        stage('Test') {
            steps {
                script {
                    def password = new hudson.util.Secret('admin')
                    def username = 'admin'
                    triggerRemoteJob job: "http://localhost:8080/job/test", auth: TokenAuth(apiToken: password, userName: username)
                }
            }
        }
    }
}
Related