Skip to content

Instantly share code, notes, and snippets.

@snyk-omar
Created May 10, 2022 19:45
Show Gist options
  • Save snyk-omar/257bfafe76c66dadd2b206bcd7921de9 to your computer and use it in GitHub Desktop.
Save snyk-omar/257bfafe76c66dadd2b206bcd7921de9 to your computer and use it in GitHub Desktop.
Delete all projects other than Snyk Code projects.
import httpx
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 non-Snyk Code project IDs in an organization."""
resp = client.post(f"/org/{org_id}/projects")
# Only get the project_ids of projects that are not Snyk Code projects
project_ids = [
project["id"]
for project in resp.json()["projects"]
if project["type"] != "sast"
]
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