Skip to content

GitHub Action之清理

清理 github action 执行后 workflow(action/run)或 deployment 记录

基本思想:通过 github api 获得对应的记录,jq 解析获得 id,之后提交删除请求。

清理 workflow和deployment

参考脚本:

Bash
#!/usr/bin/env bash
set -eu

# 需要填入token,用户名和对应仓库
TOKEN=""
OWNER="user-name"
REPO="repo-name"

MAX_TRIES=1 # 约等于总数/每次返回数量(约25个,不恒定),约等于页面
WAIT_TIME=2 # 等待时间(秒)

# 两者选择一个
API="deployments"
API="actions/runs"

URL="https://api.github.com/repos/$OWNER/$REPO/$API"

# 支持别名
# macos: brew install coreutils; 使用gdate支持-d
shopt -s expand_aliases
alias date=gdate
# 保留某些ID或最近几天的不删除 (-u utc时间)
ignore_id_list=("id1" "id2")
ignore_date=$(date -u -d "10 days ago"  +"%Y-%m-%dT%H:%M:%SZ")
ignore_timestamp=$(date -d "$ignore_date" +%s)

function _jq() {
    echo ${row} | base64 --decode | jq -r ${1}
}

echo "REPO=${OWNER}/${REPO}, API=${API}"
echo "Ignore: ${ignore_id_list[@]} || time <= ${ignore_date}"

for ((tries = 1; tries <= MAX_TRIES; tries++)); do
    request_results=$(curl -s -H "Authorization: token $TOKEN" "${URL}")

    if [[ $API == "deployments" ]] then
        rows=$(echo "$request_results" | jq -r '.[] | @base64')
    else
        rows=$(echo "$request_results" | jq -r '.workflow_runs[] | @base64')
    fi
    echo -e "\n==> ROUND = $tries/$MAX_TRIES"
    for row in $rows; do
        # jq解析得到id和时间
        action_id=$(_jq '.id')
        created_at=$(_jq '.created_at')
        created_at_timestamp=$(date -d "$created_at" +%s)

        # 保留列表中ID
        if [[ " ${ignore_id_list[@]} " =~ " $action_id " ]]; then
            echo "--> Skipping ID = $action_id AT $created_at"
            continue
        fi

        # 保留最新的
        if [[ $created_at_timestamp -ge $ignore_timestamp ]]; then
            echo "--> Skipping ID = $action_id AT $created_at"
            continue
        fi

        # 删除请求
        echo "--> Deleting ID $action_id AT $created_at"
        curl -X DELETE -s -H "Authorization: token $TOKEN" "${URL}/$action_id"
    done

    # 等待几秒后再次请求
    if [[ $tries -eq $MAX_TRIES ]]; then
        echo -e "==> Finished \n"
        break
    fi
    echo -e "==> Sleep $tries / $MAX_TRIES \n" && sleep $WAIT_TIME
done

echo "Done"

Comments