At times we need to delete old artifacts from gitlab ci builds which are no longer required. It's really tiresome to go on each job page, and delete it manually.

I researched on this a bit, and came up with a simple shell script that can help us achieve the same.

#!/bin/bash
project_id="1234" # project_id, find it here: https://gitlab.com/[organization name]/[repository name] at the top underneath repository name

token="YOUR_TOKEN" # your personal access token
server="SERVER_ADDRESS" # gitlab.com or gitlab.example.in
start_job=280493736  # first job ID
end_job=295616007  # last job ID

for job_id in $(jot - $start_job $end_job)
do
	echo "$job_id"
	URL="https://$server/api/v4/projects/$project_id/jobs/$job_id/erase"
	echo "$URL"
	curl --request POST --header "PRIVATE-TOKEN:${token}" "$URL"
	echo "\n"
done

Note that, this approach is better suited for self hosted gitlab instances, because here, we are trying to delete jobs one by one, and this could take really long time if gitlab.com is being used (the job ids are incremented across all users).

We can do better off-course. We can first gather all jobs which have an artifact, and hit api for those jobs directly instead of iterating sequentially.

I have written up a ruby job to help achieve the same.

Download the file, edit it and enter your token and project_id on line 3, 4 respectively.

This script can be run by executing ruby clear_gitlab_artifacts.rb . You don't need any specific permission to execute it. You need however, httparty gem installed in your system. You can find it at https://github.com/jnunemaker/httparty