Skip to content

Instantly share code, notes, and snippets.

@milhauscz
Forked from liveaverage/remove_gitlab_artifacts.sh
Last active September 8, 2022 12:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milhauscz/78c0f72d92e4c93632254f36bfb6256d to your computer and use it in GitHub Desktop.
Save milhauscz/78c0f72d92e4c93632254f36bfb6256d to your computer and use it in GitHub Desktop.
Script for removing GitLab Job Artifacts.
#!/bin/bash
#
# Written by Chris Arceneaux
# GitHub: https://github.com/carceneaux
# Email: carcenea@gmail.com
# Website: http://arsano.ninja
#
# Updated by Miloš Černilovský
# GitHub: https://github.com/milhauscz
#
# Note: This code is a stop-gap to erase Job Artifacts for a project. I HIGHLY recommend you leverage
# "artifacts:expire_in" in your .gitlab-ci.yml
#
# https://docs.gitlab.com/ee/ci/yaml/#artifactsexpire_in
#
# Software Requirements: curl, jq
#
# This code has been released under the terms of the Apache-2.0 license
# http://opensource.org/licenses/Apache-2.0
# project_id, find it here: https://gitlab.com/[organization name]/[repository name] at the top underneath repository name
project_id="207"
# token, find it here: https://gitlab.com/profile/personal_access_tokens
token="9hjGYpwmsMfBxT-Ghuu7"
server="gitlab.com"
# Retrieving Jobs list page count
total_pages=$(curl -sD - -o /dev/null -X GET \
"https://$server/api/v4/projects/$project_id/jobs?per_page=100" \
-H "PRIVATE-TOKEN: ${token}" | grep -Fi X-Total-Pages | sed 's/[^0-9]*//g')
# Creating list of Job IDs for the Project specified with Artifacts
job_ids=()
echo ""
echo "Creating list of all Jobs that currently have Artifacts..."
echo "Total Pages: ${total_pages}"
for ((i=0;i<=${total_pages};i++))
do
echo "Processing Page: ${i}/${total_pages}"
response=$(curl -s -X GET \
"https://$server/api/v4/projects/$project_id/jobs?per_page=100&page=${i}" \
-H "PRIVATE-TOKEN: ${token}")
length=$(jq '. | length' <<< $response)
for ((j=0;j<${length};j++))
do
if [[ $(jq ".[${j}].artifacts | length" <<< $response) > 1 ]]; then
echo "Job found: $(jq ".[${j}].id" <<< $response)"
job_ids+=($(jq ".[${j}].id" <<< $response))
fi
done
done
# Loop through each Job erasing the Artifact(s)
echo ""
echo "${#job_ids[@]} Jobs found. Commencing removal of Artifacts..."
for job_id in ${job_ids[@]};
do
response=$(curl -s -X DELETE \
-H "PRIVATE-TOKEN:${token}" \
"https://$server/api/v4/projects/$project_id/jobs/$job_id/artifacts")
echo "Processing Job ID: ${job_id} - Status: $(jq '.status' <<< $response)"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment