Introduction
The following bash script is pretty simple. It generates a CSV that lists, for each user, all the roles given to them and in which resources. It’s great for doing IAM reviews.
Note: if, for example, a user has access to a project, this scripts only lists the role granted at the project level. It doesn’t show all the resources that the user can access due to that role. This may be good or bad, depending on your final goals.
Requirements
You need to have gcloud installed and configured on the machine where you’re going to run this script.
You need to have sufficient permissions inside the org you’re going to run this script in. Something like viewer should be enough.
The script
Here it is. Save it as something like “script.sh“, run a “chmod +x script.sh” if necessary and then run it using “./script.sh“
#/bin/bash
echo "user,role,resource" > output.csv
gcloud asset search-all-iam-policies --scope=organizations/YOUR_ORG_ID_HERE | grep user: | sort | uniq | cut -c 12- | while read -r line;
do
gcloud asset analyze-iam-policy --organization=YOUR_ORG_ID_HERE --identity="user:${line}" --format="csv[no-heading](ACLs.identities.name, ACLs.accesses.role, ACLs.resources.fullResourceName)" >> output.csv
done
If you want to do the same for service accounts, then the script is:
#/bin/bash
echo "user,role,resource" > output.csv
gcloud asset search-all-iam-policies --scope=organizations/YOUR_ORG_ID_HERE | grep serviceAccount: | sort | uniq | cut -c 22- | while read -r line;
do
gcloud asset analyze-iam-policy --organization=YOUR_ORG_ID_HERE --identity="user:${line}" --format="csv[no-heading](ACLs.identities.name, ACLs.accesses.role, ACLs.resources.fullResourceName)" >> output.csv
done
Views: 73