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

如何让GitHub Actions作业在首选Runner忙碌/不可用时切换备用Runner

实现GitHub Actions Runner的故障切换/预算控制逻辑

你之前的配置把两个标签放在runs-on数组中,GitHub Actions会寻找同时拥有所有标签的Runner,因此是“且”逻辑,而非你需要的“或”逻辑。以下是两种满足需求的实现方案:

方案一:失败触发备用Runner(适用于Runner不可用/负载满场景)

通过两个Job实现顺序执行,首选Runner的Job失败(或超时)后,自动触发备用Runner的Job。

name: Build application

on:
  workflow_dispatch:

jobs:
  build-preferred:
    name: 用高性能Runner构建
    runs-on: ubuntu-latest-large
    continue-on-error: true  # 允许Job失败,不中断整个工作流
    timeout-minutes: 10  # 设置超时,避免因Runner负载过高无限等待
    steps:
      - name: 拉取代码
        uses: actions/checkout@v4
      # 替换为你的实际构建步骤
      - name: 执行构建
        run: |
          echo "正在高性能Runner上构建..."
          # 你的构建命令,比如 npm run build 或 make

  build-fallback:
    name: 用标准Runner构建(备用)
    runs-on: ubuntu-latest
    needs: build-preferred
    # 仅在首选Job失败或取消时触发
    if: needs.build-preferred.result == 'failure' || needs.build-preferred.result == 'cancelled'
    steps:
      - name: 拉取代码
        uses: actions/checkout@v4
      # 与首选Job完全相同的构建步骤
      - name: 执行构建
        run: |
          echo "正在标准Runner上构建..."
          # 你的构建命令

关键说明

  • continue-on-error: true 确保首选Job失败后,工作流不会直接终止。
  • timeout-minutes 设置超时时间,当首选Runner长时间无法承接任务(比如负载满),Job会自动标记为失败,触发备用流程。
  • 两个Job的构建步骤需要保持一致,确保最终产物等价。

方案二:提前判断条件选择Runner(适用于预算控制场景)

如果需要根据预算剩余量提前选择Runner,可以先执行一个前置Job判断条件,再动态指定Runner。

name: Build application

on:
  workflow_dispatch:

jobs:
  check-budget:
    name: 检查高性能Runner预算
    runs-on: ubuntu-latest
    outputs:
      use_preferred: ${{ steps.budget-check.outputs.use_preferred }}
    steps:
      - name: 查询预算剩余
        id: budget-check
        run: |
          # 替换为你的预算查询逻辑:
          # 比如调用GitHub API查询托管Runner的使用额度,或内部预算系统接口
          # 示例:假设查询后返回是否可使用首选Runner
          budget_remaining=true  # 实际场景替换为真实判断结果
          echo "use_preferred=$budget_remaining" >> $GITHUB_OUTPUT

  build:
    name: 执行构建
    needs: check-budget
    # 根据预算结果动态选择Runner
    runs-on: ${{ needs.check-budget.outputs.use_preferred == 'true' && 'ubuntu-latest-large' || 'ubuntu-latest' }}
    steps:
      - name: 拉取代码
        uses: actions/checkout@v4
      - name: 执行构建
        run: |
          echo "正在${{ runner.name }}上构建..."
          # 你的构建命令

关键说明

  • 前置Jobcheck-budget负责判断是否还能使用高性能Runner,结果通过outputs传递给后续Job。
  • 主构建Job通过表达式动态选择runs-on的值,无需等待失败,执行效率更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 08:03:22