[Python] python how to check if a user email is added in gcp project's iam

Discussão em 'Python' iniciado por Stack, Novembro 28, 2024.

  1. Stack

    Stack Membro Participativo

    # Replace with your own service account key file path
    SERVICE_ACCOUNT_FILE = "/home/myuser/credentials_gcp.json"
    from google.oauth2 import service_account
    from googleapiclient.discovery import build
    import os
    os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = SERVICE_ACCOUNT_FILE

    # Define the required scopes
    SCOPES = ['https://www.googleapis.com/auth/cloud-platform']

    # Authenticate using the service account
    credentials = service_account.Credentials.from_service_account_file(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)

    # Build the IAM service
    service = build('iam', 'v1', credentials=credentials)

    # List all users in the IAM policy
    def list_iam_users():
    users = []
    request = service.projects().serviceAccounts().list(name='projects/my-project')
    while request is not None:
    response = request.execute()
    for account in response.get('accounts', []):
    users.append(account['email'])
    request = service.projects().serviceAccounts().list_next(previous_request=request, previous_response=response)
    return users

    print(list_iam_users())



    Above code works to list service account but i want to check if user exist or not. "service.users()" does not exist. Is there any other fun or library to know if a user exist in iam?

    Continue reading...

Compartilhe esta Página