Jenkins中含git clone的脚本通过withCredentials执行遇权限拒绝如何解决?
问题描述
我有一个包含git clone命令的脚本,已经通过Jenkins UI将SSH凭据存储在Jenkins凭据管理中,尝试用withCredentials组件包裹脚本执行来检出代码,但遇到权限拒绝错误。
我的代码示例:
withCredentials([sshUserPrivateKey(credentialsId: 'test', keyFileVariable: 'SSH_KEYFILE', passphraseVariable: '', usernameVariable: 'SSH_USERNAME')]) { sh 'git clone ssh://bitbucket.test.com:4444/test/test' }
错误输出:
Permission denied (publickey). fatal: Could not read from remote repository.
Please make sure you have the correct access rights and the repository exists.
解决方法
1. 让Git明确使用指定的SSH密钥文件
当前代码没有告知Git要使用withCredentials导出的SSH_KEYFILE私钥,Git会默认调用Jenkins agent上的默认SSH密钥(通常不存在或无权限),导致认证失败。修改sh命令,通过GIT_SSH_COMMAND环境变量指定私钥:
withCredentials([sshUserPrivateKey(credentialsId: 'test', keyFileVariable: 'SSH_KEYFILE', passphraseVariable: '', usernameVariable: 'SSH_USERNAME')]) { sh ''' GIT_SSH_COMMAND="ssh -i $SSH_KEYFILE -o StrictHostKeyChecking=no" git clone ssh://bitbucket.test.com:4444/test/test ''' }
-o StrictHostKeyChecking=no用于避免首次连接时的主机密钥确认提示,若需要严格校验可移除该参数,但需提前在Jenkins agent上配置目标主机的密钥。
2. 验证凭据与权限的正确性
- 确认Jenkins中存储的凭据ID
test无误,且该凭据对应的SSH公钥已添加到Bitbucket的用户SSH密钥或仓库部署密钥中:- 个人仓库:将公钥添加到你的Bitbucket账号设置的SSH密钥列表;
- 团队仓库:添加为仓库的部署密钥(clone操作至少需要读权限)。
- 检查
git clone的SSH地址是否正确:确认主机地址、端口、仓库路径无拼写错误,Bitbucket的SSH端口是否确实为4444(默认是22,自定义端口需确保配置一致)。
3. 更简洁的方式:使用sshAgent组件
Jenkins提供的sshAgent组件可自动管理SSH密钥代理,无需手动指定密钥文件,适配多数场景:
sshAgent(['test']) { sh 'git clone ssh://bitbucket.test.com:4444/test/test' }
该方式会自动将指定凭据的私钥加载到SSH代理中,Git会直接使用代理内的密钥完成认证。
内容的提问来源于stack exchange,提问作者newjenkinsuser
相关产品推荐
相关产品推荐

