简体   繁体   中英

Any idea of how to list gcp service account keys using python

I need a list of all service account keys in all gcp projects within an organization. What i am looking for is a list of user managed service account keys that are active...Below is the code i am using


Not sure what is missing, i don't see user managed service account keys, i only see system managed. How can i get a list of user managed service account keys??

You're calling the projects.serviceAccounts.keys.list method with an (optional?) KeyType of SYSTEM_MANAGED but you want USER_MANAGED

I encourage you to jettison all the subprocess stuff. It's entirely redundant, makes your code unnecessary complex and problematic.

Example
import google.auth

from googleapiclient import discovery


credentials, project = google.auth.default()

crm = discovery.build(
    "cloudresourcemanager",
    "v1",
    credentials=credentials
)
iam = discovery.build(
    "iam",
    "v1",
    credentials=credentials
)

projects_list_rqst = crm.projects().list()

while projects_list_rqst is not None:
    projects_list_resp = projects_list_rqst.execute()
    projects = projects_list_resp.get("projects",[])

    for project in projects:
        project_id = project["projectId"]
        print(f"Project: {project_id}")
        name="projects/{project_id}".format(project_id=project_id) 
        sa_list_rqst = iam.projects().serviceAccounts().list(
            name=name
        )

        while sa_list_rqst is not None:
            sa_list_resp = sa_list_rqst.execute()
            accounts = sa_list_resp.get("accounts",[])

            for account in accounts:
                name=account["name"]
                print(f"\tAccount: {name}")
                keys_list_rqst = iam.projects().serviceAccounts().keys().list(
                    name=name,
                    keyTypes="USER_MANAGED"
                )
                keys_list_resp = keys_list_rqst.execute()
                keys = keys_list_resp.get("keys",[])

                for key in keys:
                    name=key["name"]
                    print(f"\t\tKey: {name}")
            
            sa_list_rqst = iam.projects().serviceAccounts().list_next(
                previous_request=sa_list_rqst,
                previous_response=sa_list_resp
            )

    projects_list_rqst = crm.projects().list_next(
        previous_request=projects_list_rqst,
        previous_response=projects_list_resp)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM