GCP: listing IAM roles for user, group, and service account in project and organization

When GCP operations fail due to permissions issues, checking the IAM roles assigned to a user, group, or service account becomes a necessity.

When hierarchical projects and organizations are involved it becomes even more complex.  This article will show you how to use gcloud at the project and organization level to pull IAM policies for users, groups, and service accounts.

Project level

To list the IAM policies you will need the IAM “roles/iam.roleViewer” (Role Viewer).

With these permissions, you can list the IAM roles assigned to a project level user.

project_id=$(gcloud config get project)
user="myuser@domain.com"

gcloud projects get-iam-policy $project_id --flatten='bindings[].members' --filter="bindings.members:user:${user}" --format='value(bindings.role)'

And list the IAM roles assigned to a project level service account.

project_id=$(gcloud config get project)
service_account="myserviceacct@${project_id}.iam.gserviceaccount.com"

gcloud projects get-iam-policy $project_id --flatten='bindings[].members' --filter="bindings.members:serviceaccount:${service_account}" --format='value(bindings.role)'

Organization level

To list the organization you will need the IAM “roles/resourcemanager.organizationViewer” (Organization Viewer), and to list the IAM policies you will need “roles/iam.organizationRoleViewer” (Organization Role Viewer).

With these permissions, you can list the IAM roles assigned to an organizational level user.

org_name="mydomain.com" 
org_id=$(gcloud organizations list --format='value(ID)' --filter="display_name=${org_name}")
org_user="myorguser@${org_name}"

gcloud organizations get-iam-policy $org_id --flatten='bindings[].members' --filter="bindings.members:user:${org_user}" --format='value(bindings.role)'

And list the IAM roles assigned to an organizational group.

org_name="mydomain.com"
org_id=$(gcloud organizations list --format='value(ID)' --filter="display_name=${org_name}")
org_group="myorgroup@${org_name}"

gcloud organizations get-iam-policy $org_id --flatten='bindings[].members' --filter="bindings.members:group:${org_group}" --format='value(bindings.role)'

 

REFERENCES

google ref, IAM roles for organizations