dee
dee

Reputation: 2424

Escape special character of git password in Jenkins pipeline groovy script

Jenkins pipeline fails at a stage where I do git pull "http:{username}:{password}@myrepo.github.com".

The password has a @ in it as per the password policy.

pipelinescript.groovy below

def credId = 'The id of the cred stored in Jenkins credentials'

stage('Some Stage'){
   withCredentials([usernamePassword(credId: "${cred}", passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME']){
 sh """
  git checkout ${myBranch}
  git status
  
  git pull https://${GIT_USERNAME}:${GIT_PASSWORD}@github.myorg.com/myrepo.git
 """
  }

}

GIT_PASSWORD is "@hello"

stage fails with error unable to resolve host: [email protected]

I cant encode @ to %40 and hardcode the password in the above url.

I tried the below in place of GIT_PASSWORD

echo -n $GIT_PASSWORD | od -A n -t x1 | sed 's/ /%/g' which gives %40%68%65%6c%6c%6f

git pull https://${GIT_USERNAME}:$(echo -n $GIT_PASSWORD | od -A n -t x1 | sed 's/ /%/g')@github.myorg.com/myrepo.git

not sure if a plugin is needed or installed already in my org for credential helper but tried

sh "git config --global credential.helper \"!echo password=${GIT_PASSWORD}; echo\""

Tried many things posted online, couldn't get a working solution. Please help.

Upvotes: 3

Views: 3640

Answers (1)

vijay v
vijay v

Reputation: 2076

Do like below:

git branch: 'master',
    credentialsId: 'your-credential-id',
    url: 'ssh://[email protected]/myrepo.git'

OR

How about just using the checkout scm stage. This way you don't have to be worried about special characters in your password.

stage('Some Stage') {
  steps {
   checkout([$class: 'GitSCM', 
    branches: [[name: '*/master']], 
    doGenerateSubmoduleConfigurations: false, 
    extensions: [[$class: 'CleanCheckout']], 
    submoduleCfg: [], 
    userRemoteConfigs: [[credentialsId: 'your-credential-id', url: 'https://github.myorg.com/myrepo.git']]
  ])
 }
}

The above stage will checkout master branch. If you want to checkout to some other branch then just replace the text with the branch name you'd want to checkout to.

Upvotes: 1

Related Questions