Skip to content

Instantly share code, notes, and snippets.

@rajathithan
Created April 22, 2024 09:49
Show Gist options
  • Save rajathithan/b3377866173834514d76a5f206bddfb0 to your computer and use it in GitHub Desktop.
Save rajathithan/b3377866173834514d76a5f206bddfb0 to your computer and use it in GitHub Desktop.
This code snippet will help in extracting cloud run details across all projects under a GCP Org
"""
Purpose : To retrieve details on cloud run services across all projects under an org
Author : Rajathithan Rajasekar
Date : Jan 23, 2024
"""
from googleapiclient.discovery import build
import google.auth
import csv
# Function - Retrieve all the projects under an org
def listAllProjects(Org_Id):
"""_summary_
Desc: Function to retrieve all the projects under an org
Args:
:type Org_Id: str
Return Type:
:rtype: List[dict]
"""
try:
filter = 'parent.type="organization" AND parent.id="{}"'.format(Org_Id)
prjUnderOrg = prj_client.projects().list(filter=filter).execute()
except Exception as e:
print(f"An error ocurred: {e}")
return prjUnderOrg["projects"]
#Function - Retrieve all the cloud run services under a project
def get_cr_service_in_project(PROJECT_ID):
"""_summary_
Desc: Function to retrieve all the cloud run services
under a project
Args:
:type PROJECT_ID: str
Return Type:
:rtype: None
"""
try:
cloudrun_services = (
cr_client.namespaces()
.services()
.list(parent=f"namespaces/{PROJECT_ID}".format(PROJECT_ID))
.execute()
)
except Exception as e:
print(f"An error ocurred: {e}")
else:
if "items" in cloudrun_services:
for item in cloudrun_services["items"]:
for img in item["spec"]["template"]["spec"]["containers"]:
svc_item = [
PROJECT_ID,
item["metadata"]["namespace"],
item["metadata"]["name"],
item["metadata"]["labels"]["cloud.googleapis.com/location"],
img["image"],
img["resources"]["limits"]["cpu"],
img["resources"]["limits"]["memory"],
]
svc_list.append(svc_item)
# Main Function
if __name__ == "__main__":
# Define scope and default auth credentials
AUTH_SCOPE = "https://www.googleapis.com/auth/cloud-platform"
CREDENTIALS, _ = google.auth.default(scopes=[AUTH_SCOPE])
# GCP ORG ID
Org_Id = "XXXXXXXXXXXX"
# Array Declarations
svc_list = []
svc_item = []
# Output file name
filename = "cr-imagls-frm-all-prjs-und-org.csv"
# Cloud resource manager client initialization
prj_client = build(
serviceName="cloudresourcemanager",
version="v1",
credentials=CREDENTIALS,
cache_discovery=False
)
# Cloud Run client initialization
cr_client = build(
serviceName="run",
version="v1",
credentials=CREDENTIALS,
cache_discovery=False
)
# Get Projects
prjs_in_org = listAllProjects(Org_Id=Org_Id)
# Iterate through projects list
for prj in prjs_in_org:
get_cr_service_in_project(PROJECT_ID=prj)
with open(filename,"w", newline="") as file:
writer=csv.writer(file)
field = [
"Project-Id",
"Namespace-Id",
"CR-Service-Name",
"Location",
"Container-Image",
"Cpu",
"Memory"
]
writer.writerow(field)
for entry in svc_list:
writer.writerow(entry)
print(f"Cloud run details under org - {Org_Id} are extracted")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment