Skip to content

Instantly share code, notes, and snippets.

@hwakabh
Last active February 29, 2024 05:56
Show Gist options
  • Save hwakabh/32ce58412d108dcdba129f4032e795b0 to your computer and use it in GitHub Desktop.
Save hwakabh/32ce58412d108dcdba129f4032e795b0 to your computer and use it in GitHub Desktop.
Python snippete for cleaning up GitHub deployment
import json
import os
import sys
# TODO: Should be replaced with stdlib
import requests
gh_username = 'hwakabh'
gh_reponame = 'waseda-mochida'
print('Fetching GitHub username & repository name from shell')
GH_USERNAME = os.environ.get('GH_USERNAME', None)
GH_REPONAME = os.environ.get('GH_REPONAME', None)
if (GH_USERNAME is None) or (GH_REPONAME is None):
print(' GH_USERNAME or GH_REPONAME not provides, please set environmental variable with your shell.')
sys.exit(1)
print('Fetching GitHub PAT from shell')
TOKEN = os.environ.get('TOKEN', None)
if TOKEN is None:
print(' TOKEN not provides, please set environmental variable with your shell.')
sys.exit(1)
url = f'https://api.github.com/repos/{GH_USERNAME}/{GH_REPONAME}/deployments'
header = {'authorization': 'token ' + TOKEN}
res = requests.get(url)
resjson = json.loads(res.text)
id_urls = [r['url'] for r in resjson]
if len(id_urls) != 0:
print('Following Deployements would be deactivated')
payload = {'state': 'inactive'}
post_header = {
'accept': 'application/vnd.github.ant-man-preview+json',
'authorization': 'token ' + TOKEN
}
for i in id_urls:
print(f' {i}')
requests.post(i + '/statuses', headers=post_header, json=payload)
print(' Done')
print('Deleting deployments')
for i in id_urls:
print(f' Deleting deployment id = {i} ...')
requests.delete(i, headers=header)
print(' Done')
print(f'Cleaned up all deployments in repo: {GH_REPONAME}')
else:
print(f'No environment found in repo: {GH_REPONAME}')

gh-cleanup-envs

This snippete can be used for cleaning up GitHub environments.

Prerequirements

Prepare GitHub PAT

Since the feature implemented with snippets should use GitHub Personal Access Token (PAT), we need to pass PAT to programs via environmental variables, because basically PAT, or other confidential information, should not be hard-coded for security reasons.

So, first of all, you need to newly create your PAT with your GitHub Accounts, then store with variables named TOKEN to the programs. Please refer to GitHub Official documentations to generate PAT.

Install Poetry

How to use

# Set personal access token as environmental variables in your shell
$ export TOKEN='ghp_XXXXXXXXXXXXXXX'

# Provide GitHub username & reponame to determine target URL
$ export GH_USERNAME='hwakabh'
$ export GH_REPONAME='gists'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment