我们的团队最近遇到了挑战。我们需要在 Azure Function 中克隆私有 GitHub 存储库(或者 AWS Lambda 可能会出现同样的问题),您只能运行 Python 代码,但无法访问 shell 或预安装的 Git 或 SSH 二进制文件。同时我们无法使用 PAT 令牌对 HTTPS API 进行身份验证。
注意,需要克隆存储库以获取其中的一些元数据和配置文件 - 而不是函数代码或Python包,因此requirements.txt不是我们想要的。
这怎么办?
GitPython 包支持基于 SSH 密钥的身份验证,但依赖系统 SSH 二进制文件来实现这一点。我们还没有找到让它在 Azure Functions 环境下工作的方法。
P.S> 该问题与自我回答一起发布(用于解决方案文档)。请参阅下面的答案。
我们发现以下两个项目都是纯Python的:
https://dulwich.io/(Python Git 包) 和 https://www.paramiko.org/(Python SSH 包)
有证据表明他们可以一起工作(尽管作者表示他们认为这种支持是“实验性的”并且没有被测试覆盖),并且很难获得端到端的代码示例。
经过一些后端处理后,以下代码片段起作用了:
from paramiko import RSAKey
import os
import dulwich
from dulwich import porcelain
from dulwich.contrib.paramiko_vendor import ParamikoSSHVendor
#Constants
private_key_path = "~.ssh/id_rsa_githubrepo"
repo_url = "[email protected]:myorg/myrepo.git"
local_path = "/tmp/repo"
# Load private key for SSH
private_key = RSAKey(filename=private_key_path)
ssh_kwargs = {"pkey": private_key}
def get_dulwich_ssh_vendor():
vendor = ParamikoSSHVendor(**ssh_kwargs)
return vendor
# overriding another module's method: gross! But there does not seem to be another way
dulwich.client.get_ssh_vendor = get_dulwich_ssh_vendor
# cloning
repo = porcelain.clone(repo_url, target=local_path, checkout=True)
#validation
with open(os.path.join(local_path, "README.md"), "r") as f:
print(f.read())
```