List all users in a project in Google Cloud using Python API

3k Views Asked by At

I am trying to list all users with their access levels, in a project in Google Cloud.

I am able to do so using Command Prompt command, gcloud projects get-iam-policy MY_PROJECT

However, while I try doing it using API, I get {} as response body.

Any reason why? Or, is there some other way?

TIA

1

There are 1 best solutions below

1
On BEST ANSWER

The API call you are doing (which is projects.roles.list) lists all custom roles defined in an organization or project, so it does not do the same as the command gcloud projects get-iam-policy, which retrieves the IAM policy for a project.

A trick you can use to know the API call behind a gcloud command is to use the --log-http global flag, which logs all HTTP requests and responses, so that you can check the resource being requested. If you run the gcloud command you shared adding that flag, you will see the following:

$ gcloud projects get-iam-policy MY_PROJECT --log-http
==== request start ====
uri: https://cloudresourcemanager.googleapis.com/v1/projects/MY_PROJECT:getIamPolicy?alt=json
method: POST
== headers start ==

The method behind that API call is resourcemanager.projects.getIamPolicy, and you can find its documentation page in this other link. In that same page, you can simply add MY_PROJECT as the resource and you will see that the reported output is the same as with gcloud projects get-iam-policy MY_PROJECT.

Finally, regarding your mentioning of doing this using Python, you can probably have a look at the Resource Manager Client Libraries documentation, where you will find information on how to install and use them. Then, you can check the library reference page, where you will find a detailed explanation (and examples) of each of the available methods. For example, here there is the reference for the getIamPolicy() method that you need to use.