Github Actions部署NestJS到DigitalOcean droplet时git pull失败求助
问题:Github Actions部署NestJS到DigitalOcean Droplet时git pull失败
部署任务执行git pull时持续报错:
err: fatal: could not read Username for 'https://github.com': No such device or address.
我的Github Actions YAML配置如下:
name: Deploy to DigitalOcean on: # 推送到develop分支时触发 push: branches: [develop] # PR到develop分支时触发 pull_request: branches: [develop] jobs: deploy: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v2 with: ssh-key: ${{ secrets.GH_SSH_KEY }} fetch-depth: 0 ref: develop - name: Set up Node.js uses: actions/setup-node@v3 with: node-version: '18' - name: Install dependencies run: yarn install - name: Build application run: yarn build - name: Set up Git env: GIT_AUTH_TOKEN: ${{ secrets.GH_TOKEN }} run: | git config --global user.email "${{ secrets.GH_USER_EMAIL }}" git config --global user.name "${{ secrets.GH_USERNAME }}" - name: Deploy application to DigitalOcean uses: appleboy/ssh-action@v0.1.8 with: host: ${{ secrets.STAGING_SSH_HOST }} username: ${{ secrets.STAGING_SSH_USERNAME }} key: ${{ secrets.STAGING_SSH_KEY }} script: | cd my-app git switch develop git pull echo "${{ secrets.STAGING_ENV_FILE }}" > .env npm run reload
我尝试过在Checkout步骤中指定仓库SSH地址,但没有解决问题:
- name: Checkout code uses: actions/checkout@v2 with: ssh-key: ${{ secrets.GH_SSH_KEY }} fetch-depth: 0 repository: git@github.com:My-CoPilot/my_copilot_backend.git ref: develop
解决方案
问题根源是DigitalOcean Droplet上的git拉取没有权限访问Github仓库。你在Actions中配置的SSH密钥仅作用于Github Actions runner的Checkout步骤,而Droplet本身并没有权限认证。可以通过以下几种方式解决:
方法1:在Droplet上配置SSH密钥认证
- 登录到你的DigitalOcean Droplet,生成SSH密钥(如果还没有):
ssh-keygen -t ed25519 -C "your-email@example.com" - 将生成的公钥(
~/.ssh/id_ed25519.pub)内容复制到你的Github账户「Settings → SSH and GPG keys」中,添加为新的SSH key。 - 测试连接:
看到ssh -T git@github.comHi username! You've successfully authenticated...即配置成功,之后Droplet上的git pull就能免密执行。
方法2:修改Droplet上仓库的远程地址为SSH格式
如果Droplet上的仓库当前使用的是HTTPS远程地址,将其替换为SSH格式:
cd /path/to/my-app git remote set-url origin git@github.com:My-CoPilot/my_copilot_backend.git
之后git pull会通过SSH认证,无需输入用户名密码。
方法3:在Actions脚本中临时配置Git凭证(适合HTTPS地址)
如果需要保留HTTPS地址,可以在SSH脚本中临时注入Github Token作为凭证:
修改Deploy步骤的script:
cd my-app git switch develop git config --global credential.helper 'store --file ~/.git-credentials' echo "https://${{ secrets.GH_TOKEN }}@github.com" > ~/.git-credentials git pull rm ~/.git-credentials # 可选:用完删除凭证文件,提升安全性 echo "${{ secrets.STAGING_ENV_FILE }}" > .env npm run reload
注意:确保你的GH_TOKEN有仓库的读取权限(repo权限)。
内容的提问来源于stack exchange,提问作者Ikem Ezechukwu
相关产品推荐
相关产品推荐

