Skip to content

Instantly share code, notes, and snippets.

@bluPhy
Last active August 27, 2024 16:48
Show Gist options
  • Save bluPhy/d6ee103a4f28fcb9a4f659390c3b9b5b to your computer and use it in GitHub Desktop.
Save bluPhy/d6ee103a4f28fcb9a4f659390c3b9b5b to your computer and use it in GitHub Desktop.
List all Google Cloud GCP projects in Organization
#!/usr/bin/env bash
# Google Cloud script
# This script checks in an organization for all the projects and list them
#
# Usage examples:
# list-all-projects-in-org.sh --organization 123456789
#
# Notes:
# To run this script, you need the required IAM permissions
# to list projects in the organization.
#
# Disclaimer: This is not an official Google product. The Sample code is
# provided as-is, without warranty or representation for any use or purpose,
# and is intended to serve as a model for a potential solution.
if [[ "$#" -ne 2 ]]; then
cat <<EOF
Usage: list-all-projects-in-org.sh <option...>
Options (exclusive)
--organization <organization-id>: for all the projects of the organization
EOF
exit 1
fi
function check_projects_in_organization() {
local -r org="$1"
echo "Listing projects in organization ${org}"
echo ""
local projects
projects=($(gcloud asset search-all-resources \
--asset-types="cloudresourcemanager.googleapis.com/Project" \
--scope=organizations/"${org}" \
--format='value(additionalAttributes.projectId)'))
echo "Found ${#projects[@]} project(s) in organization ${org}"
echo ""
echo "List of projects"
echo ""
# Getting the list of all projects, you can change the output fomat as documented in https://cloud.google.com/sdk/gcloud/reference/topic/formats
gcloud asset search-all-resources --asset-types="cloudresourcemanager.googleapis.com/Project" --scope=organizations/"${org}" --format="csv[separator="\\t"](additionalAttributes.projectId,displayName,folders,state)"
echo ""
}
function main() {
if [[ "$1" == "--organization" ]]; then
# Check if the organization ID is a valid decimal number and does not have leading zeros
if ! [[ "$2" =~ ^(?:[1-9][0-9]*|0)$ ]]; then
echo "Error: Invalid organization ID: $2"
exit 1
fi
check_projects_in_organization "$2"
else
echo "Unknown flag: $1"
exit 1
fi
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment