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

如何在自托管Runner服务启动时触发GitHub Action?

在Ubuntu自托管Runner启动时直接触发Action的方案

方案一:在Runner启动流程中嵌入本地构建/运行脚本

不需要依赖仓库推送或Webhook,直接在Runner服务启动后执行构建逻辑,步骤如下:

  1. 定位自托管Runner的systemd服务文件,路径一般为/etc/systemd/system/actions.runner.<你的仓库名>-<Runner名>.service
  2. 编辑该服务文件,在[Service]区块添加ExecStartPost指令,指定Runner启动后要执行的脚本路径:
    [Service]
    # 保留原有ExecStart配置
    ExecStartPost=/home/runner/startup-build.sh
    
  3. 编写构建脚本/home/runner/startup-build.sh(根据你的项目调整命令):
    #!/bin/bash
    # 切换到应用仓库目录
    cd /home/runner/my-app-repo
    # 拉取最新代码
    git pull origin main
    # 执行构建步骤
    npm install && npm run build
    # 重启应用服务(若用systemd管理)
    sudo systemctl restart my-app.service
    
  4. 给脚本添加执行权限:chmod +x /home/runner/startup-build.sh
  5. 重载systemd配置并重启Runner服务:
    sudo systemctl daemon-reload
    sudo systemctl restart actions.runner.<你的仓库名>-<Runner名>.service
    

方案二:通过GitHub API触发指定Workflow

如果希望严格通过GitHub Actions流程执行,可在Runner启动时调用API触发目标Workflow:

  1. 创建拥有repo权限的GitHub个人访问令牌(PAT),将其存入Runner本地安全路径,如/home/runner/.github-token,并设置权限:chmod 600 /home/runner/.github-token
  2. 编写API触发脚本/home/runner/trigger-workflow.sh:
    #!/bin/bash
    TOKEN=$(cat /home/runner/.github-token)
    OWNER="你的GitHub用户名/组织名"
    REPO="目标仓库名"
    WORKFLOW_FILE="build-and-deploy.yml" # 要触发的Workflow文件名
    
    curl -X POST \
      -H "Authorization: token $TOKEN" \
      -H "Accept: application/vnd.github.v3+json" \
      https://api.github.com/repos/$OWNER/$REPO/actions/workflows/$WORKFLOW_FILE/dispatches \
      -d '{"ref":"main"}'
    
  3. 同样将该脚本通过ExecStartPost添加到Runner的systemd服务中,启动时自动触发Workflow,Runner会自行承接任务执行。

注意事项

  • 确保Runner运行用户(默认runner)具备对应权限:拉取代码、执行构建命令、操作系统服务(若需重启应用)
  • 使用API触发时,需保证Runner网络可访问GitHub API,且定期轮换PAT避免泄露

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 01:31:03