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

如何在GitHub Actions作业间共享SonarQube缓存且不跨工作流复用

解决方案

要实现仅当前工作流复用缓存,同一PR重跑或不同PR完全隔离缓存的需求,核心是让每个工作流运行的缓存key唯一,避免不同运行复用缓存。具体修改如下:

修改缓存Key配置

原配置中缓存key是固定的report-task,这会导致所有工作流运行共享同一缓存。我们需要用GitHub Actions提供的唯一运行标识符github.run_id来生成专属key,每个工作流运行的github.run_id都不重复,这样缓存就只会在当前工作流的两个作业间共享,不会被其他运行复用。

修改后的完整配置

name: SonarQube
on:
  push:
    branches:
      - master # or the name of your main branch
  pull_request:
    types: [opened, synchronize, reopened]
concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  scan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
      - name: Set up JDK 11
        uses: actions/setup-java@v3
        with:
          java-version: 11
          distribution: corretto
          cache: gradle
      - name: Build and analyze
        env:
          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
          SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}
        run: ./gradlew --info sonar -Dsonar.host.url=$SONAR_HOST_URL -Dsonar.login=$SONAR_TOKEN
      - name: Cache report
        uses: actions/cache@v3
        with:
          path: build/sonar/
          key: sonar-report-${{ github.run_id }} # 修改为带唯一运行ID的缓存key
  qualityCheck:
    needs: scan
    runs-on: ubuntu-latest
    steps:
      - name: Get cache report
        uses: actions/cache@v3
        with:
          path: build/sonar/
          key: sonar-report-${{ github.run_id }} # 与scan作业的缓存key保持完全一致
      - name: Quality Gate check
        id: sonarqube-quality-gate-check
        uses: sonarsource/sonarqube-quality-gate-action@master
        # Force to fail step after specific time.
        timeout-minutes: 5
        with:
          scanMetadataReportFile: build/sonar/report-task.txt
        env:
          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
          SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}

关键说明

  • github.run_id是GitHub为每个工作流运行分配的唯一整数ID,无论同一PR重跑还是不同PR的运行,这个ID都不会重复,确保缓存完全隔离。
  • 两个作业使用相同的key,保证qualityCheck作业能准确读取到当前工作流scan作业生成的缓存报告,同时不会和其他运行的缓存混淆。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 14:56:30