Skip to content

Instantly share code, notes, and snippets.

@randysecrist
Created November 10, 2020 17:42
Show Gist options
  • Save randysecrist/cd17c80a8c4f45f7faa1543907dec3c0 to your computer and use it in GitHub Desktop.
Save randysecrist/cd17c80a8c4f45f7faa1543907dec3c0 to your computer and use it in GitHub Desktop.
clean gitlab artifacts
#! /usr/bin/ruby
begin
require 'net/http'
require 'json'
rescue LoadError
puts 'Required dependencies are not installed. Please install the following:'
puts '\'net/http\', \'json\''
puts 'Then try again.'
exit
end
# --------- PARAMS --------- #
if ARGV.length() != 2
puts 'Invalid input arguments. Please specify the following arguments:'
puts '[gitlab private token] [gitlab project id]'
exit
end
$api_token = ARGV[0]
$project_id = ARGV[1]
# ---------- FUNCTIONS --------- #
def get_jobs
puts "Loading job page " + ($job_page).to_s
jobs_uri = URI("https://gitlab.com/api/v4/projects/"+$project_id+"/jobs?per_page=25&page="+$job_page.to_s)
$job_page += 1
Net::HTTP.start(jobs_uri.host, jobs_uri.port, :use_ssl => true) do |http|
jobs_req = Net::HTTP::Get.new jobs_uri
jobs_req['PRIVATE-TOKEN'] = $api_token
jobs_res = http.request jobs_req
if jobs_res.code == "200"
data = JSON.parse(jobs_res.body())
if data.length() > 0
return data
end
end
return nil
end
def delete_artifacts(job_id)
puts "Removing artifacts for job " + job_id
jobs_uri = URI("https://gitlab.com/api/v4/projects/"+$project_id+"/jobs/"+job_id+"/artifacts")
Net::HTTP.start(jobs_uri.host, jobs_uri.port, :use_ssl => true) do |http|
jobs_req = Net::HTTP::Delete.new jobs_uri
jobs_req['PRIVATE-TOKEN'] = $api_token
jobs_res = http.request jobs_req
return jobs_res.code == "204"
end
end
# ----------- LOGIC ---------- #
# Get jobs
$job_page = 1
while jobs = get_jobs()
# Loop through jobs
for job in jobs
# Delete artifacts
job_id = job['id']
loop do
if delete_artifacts(job_id.to_s)
break
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment