Reputation: 647
I am trying to get a list of all GCP projects on the domain and the project owners and export it to a CSV so I can throw it into a google sheet. Getting a list is simple enough, but I can't find a way to get the owners for each project.
Upvotes: 3
Views: 4429
Reputation: 1160
The problem of applying a --filter
with gcloud
is that it'll throw an error if the key does not exist, hence I have applied jq
to achieve the same.
here is the script I used:
#!/bin/bash
echo "projectId|projectnumber|parentId|lifecycleState|owners|billingEnabled|billingAccountName"
for project in $(gcloud projects list --format="value(projectId)" --sort-by=projectId)
do
PROJECT_DETAILS=$(gcloud projects describe $project --format="value[separator='|'](projectId,projectNumber,parent.id,lifecycleState)")
OWNERS=$(gcloud projects get-iam-policy $project --flatten="bindings[].members[]" --format=json |jq -c '.[] | select(.bindings.role| . and contains("roles/owner")) | .bindings.members' | tr '\n' ',')
BILLING_DETAILS=$(gcloud beta billing projects describe $project --format="value[separator='|'](billingEnabled,billingAccountName)")
echo "$PROJECT_DETAILS|$OWNERS|$BILLING_DETAILS"
done
Save the above file as a shell script and make it executable and run
chmod +x ./get_list_of_projects.sh
./get_list_of_projects.sh
output:
projectId|projectnumber|parentId|lifecycleState|owners|billingEnabled|billingAccountName
aerobic-mile-12345|99xxxxxxxxxx|35xxxxxxxxx|ACTIVE||False|billingAccounts/xxxxxx-xxxxxx-xxxxxx
alien-lattice-12345|64xxxxxxxxxx|35xxxxxxxxx|ACTIVE|"user:[email protected]",|False|
am-test|11xxxxxxxxxx|35xxxxxxxxx|ACTIVE|"serviceAccount:[email protected]",|True|billingAccounts/xxxxxx-xxxxxx-xxxxxx
Upvotes: 2
Reputation: 40091
ROLE="roles/owner"
for PROJECT in $(\
gcloud projects list \
--format="value(projectId)" \
--filter="projectId ~ something")
do
printf "%s:\n" ${PROJECT}
gcloud projects get-iam-policy ${PROJECT} \
--flatten="bindings[].members[]" \
--filter="bindings.role=${ROLE}" \
--format="value(bindings.members)"
printf "\n"
done
For completeness, using the excellent jq which is both more general-purpose and -- I think -- easier to use:
for PROJECT in $(\
gcloud projects list \
--format="value(projectId)" \
--filter="projectId ~ something")
do
printf "%s:\n" ${PROJECT}
gcloud projects get-iam-policy ${PROJECT} --format="json" \
| jq -r '.bindings[] | select(.role=="roles/owner") | .members[]'
printf "\n"
done
Upvotes: 4