Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define credential parameter in parameters in Jenkins declarative pipeline?

I Currently using Jenkins Delarative pipeline with a parameterised build

pipeline {
    agent any
    parameters {
        booleanParam(name: 'cleanDB',defaultValue: false,description: 'should clean db ?' )
        string(name: 'host',defaultValue: 'xyx',description: 'DB Host')
    }
    stages {
        stage('Build') {
            steps {
                sh 'mvn verify'
            }
        }
        stage('Execute') {
            steps {
                withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'CREDENTIALS', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']])
                        {
                            sh "ant " +"-Ddb.clean=${params.cleanDB} -Ddb.host=${params.host} -Ddb.userid=$USERNAME \"-Ddb.password=$PASSWORD\" "
                        }
            }
        }
    }
}

when i try to build with parameters it prompts only two param cleanDB,host params.i would like it to also ask which credential parameter to take.it takes only when explicitly added though UI in parameterised build.

so how can i add credential parameter in parameters can any one share an example of defining it in below syntax.

parameters {
        booleanParam(name: 'cleanDB',defaultValue: false,description: 'should clean db ?' )
        string(name: 'host',defaultValue: 'xyx',description: 'DB Host')
credentialParam(name: 'host',description: 'Credentials')
    }
like image 297
arun kumar Avatar asked May 02 '17 11:05

arun kumar


2 Answers

While as of today (2017-08-29) jenkins docs mention only string and boolean types of possible parameters, there is some ticket that answer this question. It says to do:

parameters {
    credentials(name: 'CredsToUse', description: 'A user to build with', defaultValue: '', credentialType: "Username with password", required: true )
} 

I just tried it and it works fine. When executed for the first time it doesn't ask anything, it just creates parameter for the job. After then it asks for credentials as it should.

Naturally, it works for Declarative Pipeline syntax, so must be enveloped with 'pipeline'.

like image 111
BartBiczBoży Avatar answered Oct 24 '22 10:10

BartBiczBoży


Try the following:

withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'CREDENTIALS', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']])
                        {
                            sh 'ant -Ddb.clean=${params.cleanDB} -Ddb.host=${params.host} -Ddb.userid=$USERNAME -Ddb.password=$PASSWORD'
                        }

according to the documentation on cloudbees https://support.cloudbees.com/hc/en-us/articles/204897020-Fetch-a-userid-and-password-from-a-Credential-object-in-a-Pipeline-job-

like image 44
haschibaschi Avatar answered Oct 24 '22 10:10

haschibaschi