2025/03/01

透過 Github Actions 自動清除7天前Actions紀錄


name: Cleanup Workflow Runs

on:
  # 每週日 UTC 15:59 執行 (台灣時間 23:59)
  schedule:
    - cron: "59 15 * * 0"
  # 允許手動執行
  workflow_dispatch:

jobs:
  cleanup:
    # 改為使用自建代理
    runs-on: [self-hosted, Ubuntu, 24.04]
    permissions:
      # 允許刪除 workflow runs
      actions: write
    steps:
      - name: Install GitHub CLI
        run: |
          sudo apt update
          sudo apt install -y gh jq

      - name: Authenticate GitHub CLI
        run: echo "${{ secrets.GITHUB_TOKEN }}" | gh auth login --with-token

      - name: Get workflow runs from last week
        run: |
          # 設定刪除 7 天前的 workflow runs
          SEVEN_DAYS_AGO=$(TZ=UTC date -d "7 days ago" +%s)

          # 取得目前 repository 內所有 workflows
          gh api repos/${{ github.repository }}/actions/workflows | jq -r '.workflows[].id' > workflows.txt

          # 清空刪除列表
          > runs_to_delete.txt

          # 迴圈檢查每個 workflow,刪除超過 7 天的 workflow runs
          while read WORKFLOW_ID; do
            gh api --paginate repos/${{ github.repository }}/actions/workflows/$WORKFLOW_ID/runs | \
            jq -r --argjson SEVEN_DAYS_AGO "$SEVEN_DAYS_AGO" '
              .workflow_runs[] | select((.created_at | fromdateiso8601) < $SEVEN_DAYS_AGO) | .id' >> runs_to_delete.txt
          done < workflows.txt

      - name: Display need delete workflow runs
        run: cat runs_to_delete.txt

      - name: Delete old workflow runs
        run: |
          if [ -s runs_to_delete.txt ]; then
            while read RUN_ID; do
              echo "Deleting workflow run ID: $RUN_ID"
              gh api --method DELETE repos/${{ github.repository }}/actions/runs/$RUN_ID
            done < runs_to_delete.txt
          else
            echo "No workflow runs to delete."
          fi