Last active
December 12, 2023 12:23
-
-
Save mgerhardy/a2b3f62c6bc3517536a4b998ea0e7ac7 to your computer and use it in GitHub Desktop.
This script allows to delete old gitlab pipelines that still use disk space for the artifacts, build logs and so on
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# | |
# This script allows to delete old gitlab pipelines that still use disk space for the artifacts, build logs and so on. | |
# It will keep the last 100 pipelines. Make sure to modify your PRIVATE_TOKEN, your PROJECT_ID and your GITLAB_URL. | |
# | |
# If you want to run the script in dry mode - set _dryrun to 1 - it won't delete anything in that case, but just you the | |
# pipeline ids it would delete | |
# | |
# Used in combination with https://github.com/K-MailOrder/gitlab-migration to reduce the size of a gitlab instance | |
# before doing the migration. | |
# | |
# License: WTFPL | |
# | |
set -euo pipefail | |
# Replace these variables with your GitLab credentials and project details | |
GITLAB_URL="https://gitlab.xxx.com" | |
PRIVATE_TOKEN="YOURTOKEN" | |
# your gitlab project id to get the pipelines from | |
PROJECT_ID="1" | |
# keep this amount of pipelines - can't be 0 and must be smaller or equal to 100 | |
KEEP="100" | |
## | |
## Internal vars | |
## | |
_dryrun=0 | |
# start from this page on to delete the pipelines - keep anything that is on page 1 | |
# note: if you set this higher, you will keep (_page-1)*KEEP pipelines. | |
_page=2 | |
while true; do | |
# Get a list of all pipelines for the project | |
pipelines=$(curl -s --header "PRIVATE-TOKEN: $PRIVATE_TOKEN" "$GITLAB_URL/api/v4/projects/$PROJECT_ID/pipelines?page=${_page}&per_page=$KEEP") | |
# Check if pipelines is empty | |
if [ "$(echo "$pipelines" | jq '. | length')" -eq 0 ]; then | |
echo "No pipelines found. Exiting..." | |
break | |
fi | |
# Loop through each pipeline and delete it | |
for pipeline_id in $(echo "$pipelines" | jq -r '.[].id' | sort -n); do | |
echo -n "Deleting pipeline $pipeline_id... " | |
if [ ${_dryrun} -eq 1 ]; then | |
echo " [dryrun]" | |
else | |
response=$(curl -s --write-out "%{http_code}" --output /dev/null --request DELETE --header "PRIVATE-TOKEN: $PRIVATE_TOKEN" "$GITLAB_URL/api/v4/projects/$PROJECT_ID/pipelines/$pipeline_id") | |
if [ "$response" -eq 204 ]; then | |
echo " [done]" | |
else | |
echo " [failed]" | |
exit 1 | |
fi | |
fi | |
done | |
# advance here only - as the script would not end otherwise | |
if [ ${_dryrun} -eq 1 ]; then | |
((_page++)) | |
fi | |
done | |
echo "All pipelines deleted successfully - kept $KEEP pipelines." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment