简体   繁体   中英

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: 4hello@github.myorg.com

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.

Do like below:

git branch: 'master',
    credentialsId: 'your-credential-id',
    url: 'ssh://git@github.myorg.com/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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM