Ashley
Ashley

Reputation: 1629

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?

Upvotes: 2

Views: 10882

Answers (2)

Ashley
Ashley

Reputation: 1629

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.

Upvotes: 0

Mark Bidewell
Mark Bidewell

Reputation: 407

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}" 
    }   
  }     
}

Upvotes: 3

Related Questions