How to use multiple credentials in withCredentials in Jenkins Pipeline

JenkinsJenkins PipelineCredentials

Jenkins Problem Overview


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'?

Jenkins Solutions


Solution 1 - Jenkins

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

Solution 2 - Jenkins

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlvthilloView Question on Stackoverflow
Solution 1 - JenkinsVitalii VitrenkoView Answer on Stackoverflow
Solution 2 - JenkinsMaxView Answer on Stackoverflow