Username/password credentials in activeChoiceReactiveParam in a pipellineJob (JobDSL)?

In Jenkins I have username/password credential named ‘jenkins-user’. How do I use those credentials with e.g. curl in pipelineJob JobDSL like below:

pipelineJob("my-pipeline") {
  parameters {  
    credentialsParam('jenkins-user') {
        type('com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl')
        required()
        defaultValue('jenkins-user')
        description('Jenkins username/password')
    }    

    activeChoiceReactiveParam('test') {
        choiceType('SINGLE_SELECT')
        groovyScript {
            script('''
              try {
                def curlCmd = "curl -u$JENKINS_USER:$JENKINS_PASS host".execute()
                def result = curlCmd.text
              } catch (Exception e){
                 e.printStackTrace();
              }                
            ''')
            fallbackScript('"fallback choice"')
        }
        referencedParameter('test')
    }
  }
}

What I am missing there is the binding to env var part like here:

but I don’t see how I can use withCredentials in a JobDSL pipeline job.

Any suggestions?

since the script block in the parameter does not run directly in the pipeline, but instead at the build with parameters configuration page, then you cannot use withCredentials, within the block.

In that case you would have to look up the credentials within the script, based on the reference value, something like:

import jenkins.model.*

def jenkinsCredentials = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
        com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials.class,
        Jenkins.instance,
        null,
        null
);

def credential = jenkinsCredentials.findResult { it.id == MY_REFERENCED_PARAMETER ? it : null }

I would suggest to work on the snippets using the /script page and then move it to the parameter once happy with the result.

I hope it helps :slight_smile:

And here is a bit more pipeline, then you should be able to use the userpass variable in the curl command:

properties([
    parameters([
        choice(
            name: 'MY_CREDENTIAL',
            choices: [
                'user1',
                'user2'
            ]
        ),
        [$class: 'CascadeChoiceParameter', 
            choiceType: 'PT_SINGLE_SELECT', 
            description: 'Select the Server from the Dropdown List', 
            filterLength: 1, 
            filterable: true, 
            name: 'Server', 
            randomName: 'choice-parameter-5631314456178619', 
            referencedParameters: 'MY_CREDENTIAL', 
            script: [
                $class: 'GroovyScript', 
                fallbackScript: [
                    classpath: [], 
                    sandbox: false, 
                    script: 
                        'return[\'Could not get Environment from Env Param\']'
                ], 
                script: [
                    classpath: [], 
                    sandbox: false, 
                    script: 
                        ''' 
                        import jenkins.model.*
                        
                        def jenkinsCredentials = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
                                com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials.class,
                                Jenkins.instance,
                                null,
                                null
                        );
                        
                        def userpass = jenkinsCredentials.findResult { it.id == MY_CREDENTIAL ? it : null }
                        ["entry": "username: "  + userpass.username + " password: " + userpass.password]
                        '''
                ]
            ]
        ]
    ])
])

pipeline {
    agent any

    stages {
        stage('Hello') {
            steps {
                echo 'Hello World'
            }
        }
    }
}

Here is a image of what the snippet above should accomplish :crossed_fingers:
output

Btw you may want to use the project itself instead of Jenkins.instance so it takes into account folder credentials too.

1 Like

Thanks it works I just had to add:

def password=creds.password.getPlainText()

without that I get:

2021-11-21 18:30:00.855+0000 [id=12]	WARNING	hudson.util.Secret#toString: Use of toString() on hudson.util.Secret from org.codehaus.groovy.runtime.InvokerHelper.format(InvokerHelper.java:630). Prefer getPlainText() or getEncryptedValue() depending your needs. see https://www.jenkins.io/redirect/hudson.util.Secret/