Reputation: 8140
I have the following pipelines file:
node('git') {
stage('Set Git Config') {
sh 'git config --global user.email "[email protected]"'
sh 'git config --global user.name "jenkins"'
sh 'git config --global credential.helper cache'
sh "git config --global credential.helper 'cache --timeout=3600'"
}
stage('Set Git Credentials') {
git credentialsId: 'gitlab1', url: '${GITLAB1_REPO}'
git credentialsId: 'gitlab2', url: '${GITLAB2_REPO}'
}
stage('Synchronize with Gitlab2'){
sh 'git clone --bare ${GITLAB1_REPO} tfs'
dir("tfs") {
//add a remote repository
sh 'git remote add --mirror=fetch second ${GITLAB2_REPO}'
// update the local copy from the first repository
sh 'git fetch origin --tags'
// update the local copy with the second repository
sh 'git fetch second --tags'
// sync back the second repository
sh 'git push second --all'
sh 'git push second --tags'
}
}
}
Stage 1 and Stage 2 work perfectly. Stage 3 fails with permission denied.
I find this strange because on Stage 2, I can already see what the last commit was so it indicates that the credentials do work. Why aren't they working on stage 3?
This is the error I am seeing:
git clone --bare [email protected]/test.git tfs Cloning into bare repository 'tfs'... Permission denied (publickey). fatal: Could not read from remote repository.
While in stage 2, I see:
git config core.sparsecheckout # timeout=10 git checkout -f 30f1a7d1b77ef64e1cd44eab11a6ef4541c23b43 git branch -a -v --no-abbrev # timeout=10 git branch -D master # timeout=10 git checkout -b master 30f1a7d1b77ef64e1cd44eab11a6ef4541c23b43 Commit message: "test commit"
Upvotes: 2
Views: 3863
Reputation: 4678
Stage 1 - you add some settings in shell to local git
Stage 2 - you point to actual credentials to be used and use a Jenkins plugin - which would just work
Satge 3 - back to shell, no credentials provided from jenkins, so the context is slave/local jenkins user.
Solution would be to use withCredentials
for username and password or sshagent(credentials...)
for private key
// credentialsId here is the credentials you have set up in Jenkins for pushing
// to that repository using username and password.
withCredentials([usernamePassword(credentialsId: 'git-pass-credentials-ID', passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) {
sh("git tag -a some_tag -m 'Jenkins'")
sh('git push https://${GIT_USERNAME}:${GIT_PASSWORD}@<REPO> --tags')
}
// For SSH private key authentication, try the sshagent step from the SSH Agent plugin.
sshagent (credentials: ['git-ssh-credentials-ID']) {
sh("git tag -a some_tag -m 'Jenkins'")
sh('git push <REPO> --tags')
}
Upvotes: 3