Skip to content

Instantly share code, notes, and snippets.

@snyk-omar
Last active July 20, 2022 20:14
Show Gist options
  • Save snyk-omar/e343f458284d626e4c6e3b75b2dbab65 to your computer and use it in GitHub Desktop.
Save snyk-omar/e343f458284d626e4c6e3b75b2dbab65 to your computer and use it in GitHub Desktop.
Delete all projects that are deactivated in Snyk
"""
This script goes through all of your organizations in a group and deletes anything that is not active.
Please create a .env file in the same directory as this script and add the following variables:
SNYK_TOKEN = your_snyk_token
GROUP_ID = your_group_id
Afterwards, use a version of Python that is at least 3.7.
You will also need to download the following packages:
pip install httpx # for making HTTP requests
pip install python-dotenv # for reading .env files
"""
import httpx
import json
import logging
from dotenv import dotenv_values
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
CONFIG = dotenv_values()
def create_client(base_url: str) -> httpx.Client:
"""Create a client."""
limits = httpx.Limits(max_keepalive_connections=10, max_connections=20)
client = httpx.Client(
base_url=base_url,
headers={
"Content-Type": "application/json; charset=utf-8",
"Authorization": f"token {CONFIG['SNYK_TOKEN']}",
},
timeout=61,
limits=limits,
)
return client
def get_org_ids(client: httpx.Client, group_id: str) -> list:
"""Get all organization IDs."""
resp = client.get(f"/group/{group_id}/orgs")
org_ids = [org["id"] for org in resp.json()["orgs"]]
return org_ids
def get_org_project_ids(client: httpx.Client, org_id: str) -> dict:
"""Get all deactivated project IDs in an organization."""
filters = {"filters": {"isMonitored": False}}
resp = client.post(f"/org/{org_id}/projects", data=json.dumps(filters))
logging.debug(f"{resp.status_code} {resp.json()}")
# Only get the project_ids of projects that are deactivated
project_ids = [project["id"] for project in resp.json()["projects"]]
data = {"org_id": org_id, "project_ids": project_ids}
return data
def delete_project(client: httpx.Client, org_id: str, project_id: str) -> None:
"""Delete a project given the org_id and project_id."""
logging.info(f"Deleting project {project_id} from org {org_id}")
# Uncomment to delete projects
client.delete(f"/org/{org_id}/project/{project_id}")
def main() -> None:
"""Main function."""
group_id = CONFIG["GROUP_ID"]
client = create_client("https://snyk.io/api/v1")
org_ids = get_org_ids(client, group_id)
orgs_project_ids = []
for org_id in org_ids:
orgs_project_ids.append(get_org_project_ids(client, org_id))
# Deleting projects
for instance in orgs_project_ids:
for project_id in instance["project_ids"]:
delete_project(client, instance["org_id"], project_id)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment