如何配置GitHub Actions实现自动推送代码到远程服务器
报错核心原因
两个配置错误直接触发该问题:
- 选错了action适用场景:
ad-m/github-push-action是专门用于推送代码到GitHub/GitHub Enterprise托管仓库的工具,其github_url参数仅支持填写GitHub服务的HTTPS域名,不支持user@host:path格式的自有服务器SSH仓库地址,参数完全不匹配。 - 凭证逻辑冲突:配置
persist-credentials: false会清空runner内置的GitHub凭证,而该action识别到填入的地址不是合法GitHub地址时,不会读取传入的secrets.DEPLOY值,会直接尝试读取默认的GITHUB_TOKEN,读取失败就抛出看到的缺失报错。
可直接复用的正确配置
目标仓库是SSH协议的自有服务器,直接在ubuntu runner上配置SSH免密后手动执行git命令即可,逻辑透明无黑盒,不会出现第三方action的参数适配问题。
前置准备
- 本地生成一对无密码的SSH密钥对,将公钥内容追加到远程服务器
myuser用户的~/.ssh/authorized_keys文件中,确保持有私钥的客户端可以免密拉取/推送代码到myuser@mydomain.remote:/home/myuser/maps.git - 将私钥内容保存到当前GitHub仓库的Actions Secrets中,命名为
DEV_SERVER_SSH_KEY
工作流文件内容
把原来的directory-dev.yml替换为以下内容即可:
name: "Chicommons Maps Dev: Build & Release" on: push: paths: - "**" - ".github/workflows/directory-dev.yml" branches: - authentication jobs: push-to-dev-server: runs-on: ubuntu-latest steps: - name: 检出仓库代码 uses: actions/checkout@v4 with: fetch-depth: 0 - name: 配置SSH免密凭证 run: | mkdir -p ~/.ssh echo "${{ secrets.DEV_SERVER_SSH_KEY }}" > ~/.ssh/id_rsa chmod 600 ~/.ssh/id_rsa ssh-keyscan mydomain.remote >> ~/.ssh/known_hosts chmod 644 ~/.ssh/known_hosts - name: 推送代码到dev服务器 run: | git remote add dev myuser@mydomain.remote:/home/myuser/maps.git git push dev authentication
配套优化建议
当前服务器上的post-receive钩子存在逻辑漏洞,建议调整:
- 钩子开头加上
unset GIT_DIR,避免hook运行时自带的git环境变量导致后续命令路径错乱 - 把注释掉的
git --work-tree=$TEMP --git-dir=$REPO checkout -f放开,指定检出authentication分支,替换掉原来的git pull逻辑——首次部署时临时目录不是git仓库,直接执行git pull必然报错,checkout方式更稳定,不需要在临时目录维护git仓库状态。
调整后的钩子核心逻辑参考:
# The production directory TARGET="/var/www/html" # A temporary directory for deployment TEMP="/home/myuser/deploy-folder" # The Git repo REPO="/home/myuser/maps.git" # 清除继承的git环境变量 unset GIT_DIR # Deploy the content to the temporary directory mkdir -p $TEMP git --work-tree=$TEMP --git-dir=$REPO checkout -f authentication # 后续可自行添加构建、同步到TARGET目录的逻辑 ...
内容的提问来源于stack exchange,提问作者Dave
相关产品推荐
相关产品推荐

