def read_git_branch(config_id, branch):
config = RepoConfig.objects.get(id=config_id)
save_rsa_key(Credentials.objects.get(id=1).key)
git_ssh_identity_file = os.path.expanduser(KEY_FILE)
git_ssh_cmd = 'ssh -i %s' % git_ssh_identity_file
with Git().custom_environment(GIT_SSH_COMMAND=git_ssh_cmd):
with tempfile.TemporaryDirectory() as tmpdir:
repo = Repo.clone_from(config.url, tmpdir, branch=branch)
branch_obj, _ = Branch.objects.get_or_create(name=branch)
def save_rsa_key(key):
if not os.path.exists(os.path.dirname(KEY_FILE)):
os.makedirs(os.path.dirname(KEY_FILE))
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
with open(KEY_FILE, 'w') as id_rsa:
id_rsa.write(key)
os.chmod(KEY_FILE, 0o600)
预期的结果是将存储库克隆到临时目录,对其进行一些操作并删除所有文件。
相反,我得到:
debug/forkpoolworker-2]autointerrupt wait stderr:b'主机密钥验证失败。\n错误:无法从远程存储库中读取。\n\n请确保您具有正确的访问权限,并且存储库存在。\n'
git.exc.gitcommand错误:cmd(“git”)失败,原因是:退出代码(128)
命令行:git clone--branch=master-v git@gitlab.foo:bar/project.git/tmp/tmpi_w2xhgt
stderr:'主机密钥验证失败。
当我尝试直接从机器连接到同一个repo时,上面代码创建的密钥文件带有:
ssh-agent bash -c 'ssh-add /opt/app/.ssh/id_rsa; git clone git@gitlab.foo:bar/project.git'
复制repo时没有问题+主机添加到
known_hosts
在这样做之后,我的代码就如预期的那样工作了…
with Git().custom_environment(GIT_SSH_COMMAND=git_ssh_cmd):
repo = Repo.clone_from(config.url, tmpdir, branch=branch)
git.Repo.clone_from(url, repo_dir, env={"GIT_SSH_COMMAND": 'ssh -i /PATH/TO/KEY'})