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

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?

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 invoke Jenkins credentials in a jenkins scripted pipeline (not declarative)

i am trying to use jenkins scripted pipeline to invoke config file provider plugin along with fetching credentials from jenkins for the username and password, but the below doesn't seem to work.
node {
def mvnHome
def mvnSettings
stage('Prepare') {
mvnHome = tool 'maven-3.5.4'
}
stage('Checkout') {
checkout scm
}
stage('Deploy'){
def usernameLocal, passwordLocal, usr, psw
withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'xyz', passwordVariable: 'PASSWORD', usernameVariable: 'USERNAME']]) {
usernameLocal = env.USERNAME
passwordLocal = env.PASSWORD
}
configFileProvider(
[configFile(fileId: '*********', variable: 'MAVEN_SETTINGS', replaceTokens: true)])
{
usr="${usernameLocal}"
psw="${passwordLocal}"
sh "echo $usr"
sh "'${mvnHome}/bin/mvn' -s $MAVEN_SETTINGS deploy -Dserver.username="${usernameLocal}" -Dserver.password="${passwordLocal}""
}
}
}
where server.username and server.password are defined as properties under settings.xml server section for username and password.
Looks like i found out the issue and its nothing to do with withCredentials used here rather to do with the config file provider plugin. So i am able to print the credentials username correctly but somehow the config file provider is unable to substitute the variable value in the settings.xml.
so i don't get any error anymore, its just that the deployment doesn't go through with 401 unauthorized since the below in my settings.xml never gets the correct values :-
<server>
<id>snapshot</id>
<username>${server.username}</username>
<password>${server.password}</password>
</server>
Could you please advise how to resolve this?
The variables created by withCredentials are Groovy variables not environment variables. Try the following:
stage('Deploy'){
withCredentials([usernamePassword(credentialsId:'xyz', passwordVariable: 'Password', usernameVariable: 'Username')]) {
configFileProvider([configFile(fileId: 'abcde', variable:'MAVEN_SETTINGS')]) {
sh "'${mvnHome}/bin/mvn' -s $MAVEN_SETTINGS deploy -Dserver.username=${Username} -Dserver.password=${Password}"
}
}
}
Ok I figured out the solution, declare the configFileProvider entire section under the block of withCredentials and pass:
-Dserver.username='${usernameLocal}' -Dserver.password='${passwordLocal}'
(Please note single quotes). This way the values also get substituted and are outputted in the logs as masked.

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')
])

How to use multiple credentials in withCredentials in Jenkins Pipeline

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']])

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-

Resources