Search code examples
google-cloud-platformgoogle-cloud-iam

List ALL users of GCP account/Organization


I have an organization in GCP with multiple projects in it.

Is there any way to list ALL project users and their roles without having to access project by project?

I was using gcloud projects get-iam-policy PROJECTNAME, but list users for a single project, and I have a few hundreds.

Thanks.


Solution

  • You can use the following command in the Cloud Shell to fetch all projects and then show the iam-policy for each of them:

    for i in $(gcloud projects list |  sed 1d | cut -f1 -d$' '); do 
        gcloud projects get-iam-policy $i;
    done;
    

    A few clarifications about the command:

    • sed 1d removes the first row which will contain the following headers:

      PROJECT_ID | NAME | PROJECT_NUMBER

    • cut -f1 -d$' ' will fetch the first column, which is the PROJECT_ID that will be passed to the gcloud projects get-iam-policy command

    EDIT

    As you wanted to get the results in a PROJECT | MEMBERS | ROLE style, you can use the following which will create a .csv file for each project with the following structure inside: ROLES | MEMBERS. Each fille will be named PROJECT_ID.csv

    • Roles: Current role owned by the followed list of members

    • Members: List of members who own the role

    for i in $(gcloud projects list |  sed 1d | cut -f1 -d$' '); do
        echo "Getting IAM policies for project:" $i;
        echo "..........";
        (echo "ROLES,MEMBERS" && paste -d "," <(printf %s "$(gcloud projects get-iam-policy $i | yq '.bindings | .[].role' | cut -d "\"" -f2)") <(printf %s "$(gcloud projects get-iam-policy $i | yq '.bindings | .[].members | join(",")' | cut -d"\"" -f2)")) | cat >> $i.csv
     
        echo "Done. Logs created at file" $i.csv;
        echo "--------------------------------"
    done;
    

    The only requirement that may be needed to install here is yq, which you can install in your shell.

    EDIT 2:

    As requested in the comments, all the information output will go to the same .csv file following the format: PROJECT_ID | ROLE | MEMBERS

    echo "PROJECT_ID,ROLES,MEMBERS" | cat >> output.csv
    for i in $(gcloud projects list |  sed 1d | cut -f1 -d$' '); do
        echo "Getting IAM policies for project:" $i;
        echo "..........";
        paste -d "," <(printf %s "$(for j in $(seq 1 $(gcloud projects get-iam-policy $i | yq '.bindings | .[].role' | cut -d "\"" -f2 | wc -l)); do echo $i; done;)") <(printf %s "$(gcloud projects get-iam-policy $i | yq '.bindings | .[].role' | cut -d "\"" -f2)") <(printf %s "$(gcloud projects get-iam-policy $i | yq '.bindings | .[].members | join(",")' | cut -d"\"" -f2)") | cat >> output.csv
     
        echo "Done. Logs created at file" $output.csv;
        echo "--------------------------------"
    done;