How to use multiple credentials in withCredentials in Jenkins Pipeline - jenkins

I have the following step in my declarative jenkins pipeline:
I create script which comes from my resources/ folder using libraryResource. This script contains credentials for my autobuild user and for some admintest user.
stage('Build1') {
steps {
node{
def script = libraryResource 'tests/test.sh'
writeFile file: 'script.sh', text: script
sh 'chmod +x script.sh'
withCredentials([usernamePassword(credentialsId: xxx, usernameVariable: 'AUTOBUILD_USER', passwordVariable: 'AUTOBUILD_PASSWD')]){
sh './script.sh "
}
}
}
This works fine. I can use my autobuild user. Now I'm searching for the best way how I can include also the crendentials of my admintest user.
Do I have to 'nest' it with a second withCredentials part or can I add again a usernamePassword 'array'?

Sure, you can use one withCredentials block to assign multiple credentials to different variables.
withCredentials([
usernamePassword(credentialsId: credsId1, usernameVariable: 'USER1', passwordVariable: 'PASS1'),
usernamePassword(credentialsId: credsId2, usernameVariable: 'USER2', passwordVariable: 'PASS2')
]){
//...
}

Also, you can use this with $class
withCredentials([[
$class: 'AmazonWebServicesCredentialsBinding',
credentialsId: 'awsID',
accessKeyVariable: 'AWS_ACCESS_KEY_ID',
secretKeyVariable: 'AWS_SECRET_ACCESS_KEY'],
[$class: 'UsernamePasswordMultiBinding',
credentialsId: 'myID',
usernameVariable: 'USR',
passwordVariable: 'PWD']])

Related

Jenkinsfile: How to parameterise Credential Id as per branch name?

I am using credentials plugin in my Jenkinsfile like below-
stage("stage name"){
steps{
withCredentials([usernamePassword(credentialsId: 'credId', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]){
sh'''
statement 1
statement 2
'''
}
}
}
As per new requirement, I need to different credentials id as per branch name. That means if branch name is master, I should use credentialsId:'mastercred' and for other branches, I should use credentialsId:'othercred'. The code in "withCredentials" block will be the same for, the only change will be with credentialsId.
I don't want to duplicate code. Is there any way to parameterise this credentialsId?
You can read the branch name variable, and set the a credentialId variable to use on withCredentials would the work. For example:
stage("stage name"){
steps{
if (env.BRANCH_NAME == "master"){
credentialId = "mastercred"
}else
credentialId = "othercred"
}
withCredentials([usernamePassword(credentialsId: "${credentialId}", usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]){
sh'''
statement 1
statement 2
'''
}
}
}

How to access password when using multiple credentials in Jenkins Pipline?

I have the following step in my pipeline:
node('linux') {
withCredentials(
[
usernamePassword(
credentialsId: 'cred1',
passwordVariable: '1PASSWORD', usernameVariable: '1USER'
),
usernamePassword(
credentialsId: 'cred2',
passwordVariable: '2PASSWORD', usernameVariable: '2USER'
)
]
) {
script {
sh """export SUDO_PASSWORD=\$2PASSWORD
}
}
I'm trying to export the password of the credential used. I do not know ahead of time which credentials would be used (this depends on the machine that's being built on). So above, if cred1 is used I want to run sh """export SUDO_PASSWORD=\$1PASSWORD.
How do I get the password from when it depends on which credential is used?

How to get password from a credentials parameter in Jenkins pipeline job

I have a Jenkins pipeline job, and it has a Credentials Parameter of the type "Username with password". Let's call this Credentials Parameter DB_USER_CRED.
Now, I have 2 credentials of type "Username with password" stored on Jenkins already, call them DB_USER1 and DB_USER2. Hence, I have this in my job:
withCredentials([
usernamePassword(credentialsId: 'DB_USER1', usernameVariable: 'DB_USER1_NAME', passwordVariable: 'DB_USER1_PASSWORD'),
usernamePassword(credentialsId: 'DB_USER2', usernameVariable: 'DB_USER2_NAME', passwordVariable: 'DB_USER2_PASSWORD')
]){
So when a user runs the job, he/she can choose either DB_USER1 or DB_USER2 to fill in the parameter DB_USER_CRED with. And then I can tell which user was used by checking $DB_USER_CRED. But then is there a way to get the password from DB_USER_CRED? I'd like not to have to compare $DB_USER_CRED against $DB_USER1_NAME and $DB_USER2_NAME in order to find out which password to use, i.e., $DB_USER1_PASSWORD or $DB_USER2_PASSWORD. The reason being there might be 10 possible DB users that have access to this job and it is not realistic to have to compare $DB_USER_CRED to all of them. Thanks.
Found the solution: https://support.cloudbees.com/hc/en-us/articles/204897020-Fetch-a-userid-and-password-from-a-Credential-object-in-a-Pipeline-job-
So to use the example from above, the solution is:
withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: env.DB_USER_CRED, usernameVariable: 'DB_USER_CRED_USERNAME', passwordVariable: 'DB_USER_CRED_PASSWORD']])
{
// The password is $DB_USER_CRED_PASSWORD
}
My job also uses other credentials stored in Jenkins, and they can be appended this way:
withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: env.DB_USER_CRED, usernameVariable: 'DB_USER_CRED_USERNAME', passwordVariable: 'DB_USER_CRED_PASSWORD'],
usernamePassword(credentialsId: 'OTHER_CRED', usernameVariable: 'OTHER_CRED_NAME', passwordVariable: 'OTHER_CRED_PASSWORD')
])

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')
}
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'.
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-

Jenkins Multibranch Pipeline Jenkinsfile detect Git repo that launched job

I have a multi branch pipeline configuration job working fine so far....
However every single repository has exactly the same jenkinsfile except for the git repo name.
a typical jenkinsfile looks like:
node('docker-slave') {
withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'NEXUS', usernameVariable: 'NEXUS_USERNAME', passwordVariable: 'NEXUS_PASSWORD']]) {
git url: 'git#bitbucket.org:myco/myprob.git', branch: env.branch_name, credentialsId: '08df8ab41de0', variable: 'CREDENTIALS'
stage 'Test'
sh 'env > env.txt'
sh 'cat env.txt'
sh 'make verify'
}
}
What I'd like to do is detect which git repo triggered the build so I don't have to hardcode it in the jenkinsfile.
So what I'd like is to change the git line to something like (notice GIT_URL):
git url: env.GIT_URL, branch: env.branch_name, credentialsId: '08df8ab41de0', variable: 'CREDENTIALS'
This gets me closer to my eventual goal of storing my Jenkinsfile in a common location instead of having to copy it repo to repo and modify it repo to repo.
Any ideas?
Thanks
phil
it turns out that in the script the following code does exactly what I need:
checkout sum
The git url line isn't needed....
so in the end the code looks like:
node('docker-slave') {
withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'NEXUS', usernameVariable: 'NEXUS_USERNAME', passwordVariable: 'NEXUS_PASSWORD']]) {
checkout scm
stage 'Test'
sh 'make verify'
}

Resources