user12685609
user12685609

Reputation:

GCP user list using python

How I can get a list of users in account GCP using python. I can't find how I can authorize using python in account and get a list. Can anybody help me?

Upvotes: 0

Views: 2321

Answers (1)

John Hanley
John Hanley

Reputation: 81356

I am assuming that you are just getting started with Google Cloud and the Python SDKs. If you are already experienced, skip to the bottom of my answer for the actual example code.

The documentation for the Google Cloud Python SDKs can be hard to figure out. The key detail is that Google documents the APIs using automated tools. Google publishes a document that SDKs can read to automatically build APIs. This might appear strange at first, but very clever when you think about it. SDKs that automatically update themselves to support the latest API implementation.

Start with the root document: Google API Client Library for Python Docs

Near the bottom is the link for documentation:

Library reference documentation by API

For your case, listing users with IAM bindings in a project, scroll down to cloudresourcemanager. Sometimes there are multiple API versions. Usually, pick the latest version. In this case, v3.

Knowing which API to use is built from experience. As you develop more and more software in Google Cloud, the logic to the architecture becomes automatic.

Cloud Resource Manager API

The API provides multiple Instance Methods. In your case, the instance method is projects.

Cloud Resource Manager API - projects

Within projects are Instance Methods. In your case, getIamPolicy().

getIamPolicy(resource, body=None, x__xgafv=None)

Sometimes you need to review the REST API to understand parameters and returned values.

Resource Manager REST API: Method: projects.getIamPolicy

For example, to understand the response from the Python SDK API, review the response documented by the REST API which includes several examples:

Resource Manager REST API: Policy

Now that I have covered the basics of discovering how to use the documentation, let's create an example that will list the roles and IAM members.

Import the required Python libraries:

from google.oauth2 import service_account
import googleapiclient.discovery

Create a variable with your Project ID. Note: do not use Project Name.

PROJECT_ID='development-123456'

Note: In the following explanation, I use a service account. Later in this answer, I show an example using ADC (Application Default Credentials) set up by the Google Cloud CLI (gcloud).

Create a variable with the full pathname to your Google Cloud Service Account JSON Key file:

SA_FILE='/config/service-account.json'

Create a variable for the required Google Cloud IAM Scopes. Typically I use the following scope as I prefer to control permissions via IAM Roles assigned to the service account:

SCOPES=['https://www.googleapis.com/auth/cloud-platform']

Create OAuth credentials from the service account:

credentials = service_account.Credentials.from_service_account_file(
        filename=SA_FILE,
        scopes=SCOPES)

Now we are at the point to start using the API documentation. The following code builds the API discovery document and loads the APIs for cloudresourcemanager:

service = googleapiclient.discovery.build(
        'cloudresourcemanager',
        'v3',
        credentials=credentials)

Now call the API which will return a JSON response details the roles and members with bindings to the project:

resource = 'projects/' + PROJECT_ID

response = service.projects().getIamPolicy(resource=resource, body={}).execute()

The following is simple code to print part of the returned JSON:

for binding in response['bindings']:
        print('Role:', binding['role'])

        for member in binding['members']:
                print(member)

Complete example that uses ADC (Application Default Credentials):

import googleapiclient.discovery

PROJECT_ID='development-123456'

service = googleapiclient.discovery.build('cloudresourcemanager', 'v3')

resource = 'projects/' + PROJECT_ID

response = service.projects().getIamPolicy(resource=resource, body={}).execute()

for binding in response['bindings']:
        print('Role:', binding['role'])

        for member in binding['members']:
                print(member)

Complete example using a service account:

from google.oauth2 import service_account
import googleapiclient.discovery

PROJECT_ID='development-123456'

SA_FILE='/config/service-account.json'

SCOPES=['https://www.googleapis.com/auth/cloud-platform']

credentials = service_account.Credentials.from_service_account_file(
    filename=SA_FILE,
    scopes=SCOPES)

service = googleapiclient.discovery.build(
    'cloudresourcemanager', 'v3', credentials=credentials)

resource = 'projects/' + PROJECT_ID

response = service.projects().getIamPolicy(resource=resource, body={}).execute()

for binding in response['bindings']:
    print('Role:', binding['role'])

    for member in binding['members']:
        print(member)

Upvotes: 2

Related Questions