-
Notifications
You must be signed in to change notification settings - Fork 11
/
fetch-gcp-projects.sh
executable file
·62 lines (44 loc) · 1.31 KB
/
fetch-gcp-projects.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/bin/bash
#
# usage
# ./fetch-gcp-projects.sh <ORG-ID>
# will return
# ["A", "B", "C"]
#
#
# Function to list projects under a folder recursively
#
list_projects_recursive() {
local folder_id="$1"
# List projects under the current folder
printf " %s" $(gcloud projects list --filter="parent.id=$folder_id" --format="value(projectId)")
# List subfolders and call this function recursively
local subfolders=$(gcloud resource-manager folders list --folder=$folder_id --format="value(name)")
for subfolder in $subfolders; do
list_projects_recursive "$subfolder"
done
}
#
# main flow
#
if [ $# -ne 1 ]; then
echo "script must be launched with the organization id"
echo "usage $0 organizationId"
exit 1
fi
org_id=$1
projectIds=()
projectIds+=$(gcloud projects list --filter="parent.type=organization AND parent.id=$org_id" --format="value(projectId)")
# List top-level folders
folders=$(gcloud resource-manager folders list --organization=$org_id --format="value(name)")
# Iterate through the top-level folders and list projects recursively
for folder in $folders; do
projectIds+=$(list_projects_recursive "$folder")
done
projectList="["
for value in $projectIds; do
projectList="$projectList\"$value\", "
done
# Remove the trailing comma and space
projectList="${projectList%, }]"
echo $projectList