Skip to content

Instantly share code, notes, and snippets.

@varunchandak
Created January 14, 2024 10:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save varunchandak/70d6db0cf11d1de9918c01c00fb02826 to your computer and use it in GitHub Desktop.
Save varunchandak/70d6db0cf11d1de9918c01c00fb02826 to your computer and use it in GitHub Desktop.
Google Cloud Organization Folders Listing Script

Google Cloud Organization Folders Listing Script

This script is designed to recursively list all folders within a specified Google Cloud Organization. It utilizes the gcloud command-line tool to fetch and display the folder hierarchy.

Installation

Before running this script, ensure that you have the following prerequisites installed:

  1. Google Cloud SDK
  2. Bash shell (usually pre-installed on Linux and macOS)

Configuration

Before using the script, you need to authenticate with Google Cloud and set your project:

gcloud auth login
gcloud config set project YOUR_PROJECT_ID

Replace YOUR_PROJECT_ID with your actual Google Cloud project ID.

Usage

  • Open the script in a text editor.
  • Replace YOUR_ORG_ID with your actual Google Cloud Organization ID in the script.
  • Run the script in your terminal:
    ./list_folders.sh
    
    Ensure that the script has execute permissions. If not, run chmod +x list_folders.sh to make it executable.
#!/bin/bash
# Start with the organization as the parent (replace 'YOUR_ORG_ID' with your actual organization ID)
ORG_ID="YOUR_ORG_ID"
# Function to list folders recursively
list_folders() {
local parent=$1
local parent_type=$2
local folders
# Check if the parent is an organization or a folder and set the appropriate gcloud command
if [ "$parent_type" == "organization" ]; then
folders=$(gcloud resource-manager folders list --organization=${parent} --format="csv[no-heading](name,displayName)")
else
folders=$(gcloud resource-manager folders list --folder=${parent} --format="csv[no-heading](name,displayName)")
fi
# Iterate through each folder and list its sub-folders
IFS=$'\n' # Change the field separator to new line
for folder in $folders; do
IFS=, # Change the field separator to comma for parsing the CSV
read -ra fld <<< "$folder" # Read the line into an array
local id=${fld[0]}
local name=${fld[1]}
echo "$name,$id"
# Recursively list nested folders
list_folders $id "folder"
done
IFS=$' \t\n' # Reset the field separator to default
}
list_folders $ORG_ID "organization"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment