配置App Center CI时如何处理私有SPM依赖的权限问题
问题背景
App Center CI构建通过SPM管理的iOS项目时,因私有依赖使用SSH拉取,构建环境缺少对应SSH密钥,导致出现Permission denied (publickey)错误,无法克隆私有依赖仓库。错误示例:
2023-01-23 14:03:12.081 xcodebuild[1922:7455]
Writing error result bundle to /var/folders/24/8k48jl6d249_n_qfxwsl6xvm0000gn/T/ResultBundle_2023-23-01_14-03-0012.xcresult skipping cache due to an error: Failed to clone repository git@github.com:my-app/my-app.git: Cloning into bare repository '/Users/runner/Library/Caches/org.swift.swiftpm/repositories/my-app-0fe0f1ea'...git@github.com: Permission denied (publickey).fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists.
skipping cache due to an error: Failed to clone repository git@github.com:my-app/my-app.git: Cloning into bare repository '/Users/runner/Library/Caches/org.swift.swiftpm/repositories/my-app-0fe0f1ea'...
git@github.com: Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists.
xcodebuild: error: Could not resolve package dependencies: Failed to clone repository git@github.com:my-app/my-app.git: Cloning into bare repository '/Users/runner/Library/Developer/Xcode/DerivedData/MyApp-adedabdybispofpuztbywfdmxtd/SourcePackages/repositories/my-app-0fe0f1ea'...
可行解决方案
方案1:通过SSH密钥授权
生成SSH密钥对
在本地终端执行命令生成无密码的SSH密钥:ssh-keygen -t ed25519 -C "app-center-build@your-org.com"按回车跳过密码设置,生成
id_ed25519(私钥)和id_ed25519.pub(公钥)文件。添加公钥到GitHub私有依赖仓库
打开私有依赖仓库的Settings > Deploy keys页面,点击Add deploy key,粘贴公钥内容,勾选Allow write access(若构建需要更新依赖则勾选),保存。在App Center配置构建前脚本
进入App Center项目的Build > 对应构建配置 > Pre-build script,添加以下脚本(替换私钥内容为你的实际私钥,注意用\n替换私钥中的换行):# 创建.ssh目录并设置权限 mkdir -p ~/.ssh chmod 700 ~/.ssh # 写入私钥 echo "-----BEGIN OPENSSH PRIVATE KEY----- 你的私钥内容,换行用\n代替 -----END OPENSSH PRIVATE KEY-----" > ~/.ssh/id_ed25519 chmod 600 ~/.ssh/id_ed25519 # 添加GitHub到已知主机,避免首次连接确认 ssh-keyscan github.com >> ~/.ssh/known_hosts chmod 644 ~/.ssh/known_hosts
方案2:改用HTTPS+GitHub个人访问令牌(PAT)
修改SPM依赖URL
把Package.swift或Xcode项目中私有依赖的SSH URL(git@github.com:xxx/xxx.git)替换为HTTPS URL(https://github.com/xxx/xxx.git)。生成GitHub PAT
在GitHub的Settings > Developer settings > Personal access tokens页面生成令牌,勾选repo权限(读取私有仓库),保存令牌。在App Center配置环境变量与构建脚本
- 进入App Center构建配置的
Environment variables,添加GITHUB_TOKEN变量,值为生成的PAT。 - 在
Pre-build script中添加以下脚本:
该脚本会让git自动在HTTPS请求中带上令牌,实现私有仓库的授权访问。git config --global url."https://${GITHUB_TOKEN}@github.com/".insteadOf "https://github.com/"
- 进入App Center构建配置的
内容的提问来源于stack exchange,提问作者susanna

