You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Github Action CI/CD工作流SSH连接AWS EC2实例失败求助

问题排查:Github Actions部署至EC2时git pull公钥权限拒绝

错误定位

从日志看,***@github.com: Permission denied (publickey)是EC2实例执行git pull时无法访问Github私有仓库导致的,不是Github Actions连接EC2的SSH认证问题——因为已经成功执行了docker-compose down命令,说明SSH连接EC2是正常的。

核心原因

你配置的SSH密钥是给Github Actions连接EC2用的,但EC2实例本身没有配置能访问Github私有仓库的SSH权限。本地能SSH到EC2后拉代码,是因为本地环境的SSH代理转发或EC2上有你本地的密钥,但Github Actions触发的部署没有这个环境。

解决步骤

  1. 在EC2实例生成仓库访问密钥
    登录EC2,执行命令生成专属密钥(不要设置密码,避免部署交互):

    ssh-keygen -t rsa -b 4096 -f ~/.ssh/github_repo_key
    
  2. 将公钥添加到Github仓库Deploy Keys
    复制EC2上生成的公钥内容:

    cat ~/.ssh/github_repo_key.pub
    

    打开你的私有仓库,进入Settings > Deploy keys,点击Add deploy key,粘贴公钥内容,按需勾选Allow write access,保存。

  3. 配置EC2的git使用新密钥
    创建或修改~/.ssh/config文件,指定github.com使用该密钥:

    Host github.com
        IdentityFile ~/.ssh/github_repo_key
        User git
    

    同时确保项目目录下的git远程地址是SSH格式(而非HTTPS):

    cd my_repo/
    git remote set-url origin git@github.com:你的用户名/你的仓库名.git
    
  4. 验证EC2拉取权限
    在EC2上执行:

    cd my_repo/
    git pull
    

    确认能正常拉取代码。

额外检查项

  • 确保EC2上.ssh目录及文件权限正确:
    chmod 700 ~/.ssh/
    chmod 600 ~/.ssh/authorized_keys ~/.ssh/github_repo_key
    
  • 确认Github Actions的SSH步骤正确加载密钥,推荐使用webfactory/ssh-agent动作管理:
    - name: Setup SSH agent
      uses: webfactory/ssh-agent@v0.9.0
      with:
        ssh-private-key: ${{ secrets.SSH_PRIVATE_KEY }}
    

内容的提问来源于stack exchange,提问作者MrWipp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 03:03:16