Skip to content

Instantly share code, notes, and snippets.

@sefasenturk95
Last active October 7, 2021 13:26
Show Gist options
  • Save sefasenturk95/36415c0da0db6f9424183fa455569f4c to your computer and use it in GitHub Desktop.
Save sefasenturk95/36415c0da0db6f9424183fa455569f4c to your computer and use it in GitHub Desktop.
Delete artifacts automatically
import json
import urllib.request
import math
access_token = "rqtweyjhg"
org_name = "my-org"
keep_artifacts = 2
def get_all_artifacts(repo_name: str) -> []:
amount_items_per_page = 30
page = 1
result = json.loads(urllib.request.urlopen(
"https://api.github.com/repos/" + org_name + "/" + repo_name + "/actions/artifacts?access_token=" + access_token + "&page=" + str(
page)).read())
done = False
all_artifacts = []
while not done:
total_count = int(result["total_count"])
if total_count == 0:
done = True
all_artifacts = all_artifacts + result["artifacts"]
max_pages = math.ceil(total_count / amount_items_per_page)
if max_pages > page:
page = page + 1
else:
done = True
return all_artifacts
def delete_artifact(repo_name: str, artifact_id: str) -> bool:
try:
res = urllib.request.urlopen(urllib.request.Request(
url="https://api.github.com/repos/" + org_name + "/" + repo_name + "/actions/artifacts/" + artifact_id + "?access_token=" + access_token,
method='DELETE')
).getcode()
return res == 204
except urllib.error.URLError as error:
print(error)
return False
data = urllib.request.urlopen("https://api.github.com/orgs/" + org_name + "/repos?access_token=" + access_token).read()
output = json.loads(data)
for item in output:
repo_name = item["name"]
artifacts = get_all_artifacts(repo_name)
print("Amount of artifacts for repo " + repo_name + " is " + str(len(artifacts)))
if len(artifacts) <= keep_artifacts:
continue
for a in artifacts[keep_artifacts:]:
artifact_id = str(a["id"])
deleted = delete_artifact(repo_name, artifact_id)
if deleted:
print("Repo: " + repo_name + " | Artifact with id " + artifact_id + " has been deleted")
else:
print("Repo: " + repo_name + " | Something went wrong while deleting artifact with id " + artifact_id)
@kierendev
Copy link

Works perfectly! So annoying how this can't be done at all with Github. Saved me heaps of time writing my own script. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment