删除 GitLab 项目中除最新流水线之外的所有流水线

本文最后更新于 2024年2月2日

#!/usr/bin/env bash
IFS=$'\n'

if [ -z "$GITLAB_API" ]; then
    GITLAB_API=https://gitlab.com/api/v4
fi
if [ -z "$GITLAB_REMAIN" ]; then
    GITLAB_REMAIN=1
fi

usage()
{
    echo "USAGE: $0 [OPTIONS]"
    echo "OPTIONS:"
    echo "  -a, --api [API]         $GITLAB_API"
    echo "  -p, --project [PROJECT] integer or string"
    echo "  -r, --remain [REMAIN]   integer, default $GITLAB_REMAIN"
    echo "  -t, --token [TOKEN]     string, access token"
    echo "  -h, --help              display this help and exit"
    exit
}

while [ $# -gt 0 ]; do
    case "$1" in
        -a|--api)
            shift
            GITLAB_API="$1"
            ;;
        -p|--project)
            shift
            GITLAB_PROJECT="$1"
            ;;
        -r|--remain)
            shift
            GITLAB_REMAIN="$1"
            ;;
        -t|--token)
            shift
            GITLAB_TOKEN="$1"
            ;;
        -h|--help|*)
            shift
            usage
            ;;
    esac
    shift
done

if [ -z "$GITLAB_PROJECT" ]; then
    echo "missing GITLAB_PROJECT or -p, --project [PROJECT]"
    exit
fi
expr $GITLAB_PROJECT "+" 0 &>/dev/null
if [ $? -ne 0 ]; then
    GITLAB_PROJECT=${GITLAB_PROJECT//\//%2F}
fi
if [ -z "$GITLAB_TOKEN" ]; then
    echo "missing GITLAB_TOKEN or -t, --token [TOKEN]"
    exit
fi

echo "GITLAB_API=$GITLAB_API"
echo "GITLAB_PROJECT=$GITLAB_PROJECT"
echo "GITLAB_TOKEN=******"
echo "GITLAB_REMAIN=$GITLAB_REMAIN"

# https://docs.gitlab.com/ee/api/projects.html#get-single-project
echo "Deleting in project $(curl -s --request GET "$GITLAB_API/projects/$GITLAB_PROJECT" | jq -c '.web_url' -r)"
while :; do
    COUNTER=0
    # https://docs.gitlab.com/ee/api/pipelines.html#list-project-pipelines
    for PIPELINE in $(curl -s --header "PRIVATE-TOKEN: $GITLAB_TOKEN" "$GITLAB_API/projects/$GITLAB_PROJECT/pipelines?per_page=100" | jq -c '.[]'); do
        if [[ "$COUNTER" -ge "$GITLAB_REMAIN" ]]; then
            PIPELINE_ID=$(echo $PIPELINE | jq '.id')
            echo "Deleting pipeline $PIPELINE_ID"
            # https://docs.gitlab.com/ee/api/pipelines.html#delete-a-pipeline
            curl --header "PRIVATE-TOKEN: $GITLAB_TOKEN" --request "DELETE" "$GITLAB_API/projects/$GITLAB_PROJECT/pipelines/$PIPELINE_ID"
        fi
        ((COUNTER++)) || true
    done
    if [[ "$COUNTER" -le "$GITLAB_REMAIN" ]]; then
        break
    fi
done

参考

https://gist.github.com/3da4ac6c17f197c0665ada8c90d47744


删除 GitLab 项目中除最新流水线之外的所有流水线
https://blog.tqfx.org/posts/Delete-all-pipelines-except-the-latest-pipeline-in-the-GitLab-project/
作者
tqfx
发布于
2023年11月10日
许可协议