Created
February 14, 2024 15:44
-
-
Save vadirajks/621c620d7c788e1b9c58a9aa101f410f to your computer and use it in GitHub Desktop.
gcp_custom_vm.sh
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
function list_folders_recursive { | |
local folder="$1" | |
# Fetch folder names | |
local folders=$(gcloud resource-manager folders list --folder="$folder" --format="csv[no-heading](name)") | |
# Check if folders is empty | |
if [ -z "$folders" ]; then | |
return | |
fi | |
# Iterate over folder names | |
while IFS= read -r folder_name; do | |
folder_names+=("$folder_name") | |
list_folders_recursive "$folder_name" | |
done <<< "$folders" | |
} | |
tmp_folder="/tmp/custom_vms_details" | |
rm -rf $tmp_folder | |
mkdir -p $tmp_folder | |
organizations=$(gcloud organizations list --format="value(ID)" | head -n 1) | |
folder=$(gcloud resource-manager folders list --organization=$organizations | awk '/^Revx/{print $NF}' | head -n 1) | |
# Starting from the root folder (replace with the desired folder ID) | |
root_folder="${folder}" | |
folder_names=(${folder}) | |
# Collect folder names recursively | |
list_folders_recursive "$root_folder" | |
printf "%s\n" "${folder_names[@]}" | |
# Printing projects from the collected folder names | |
for folder_name in "${folder_names[@]}"; do | |
for project in $(gcloud projects list --filter parent.id:${folder_name} '--format=csv[no-heading](name,projectNumber,projectId:label=ProjectID)'); do | |
SERVICE="compute.googleapis.com" | |
STATUS=$(gcloud services list --project "${project##*,}" --enabled --filter="NAME:$SERVICE" --format="value(NAME)" 2>&1) | |
if [[ ! $STATUS == "$SERVICE" ]]; then | |
echo "Compute Engine API ($SERVICE) is DISABLED or unavailable." | |
continue | |
fi | |
#gcloud compute instances list --project "${project##*,}" --filter="machineType:custom" --format="csv(NAME,ZONE,MACHINE_TYPE,PREEMPTIBLE,INTERNAL_IP,EXTERNAL_IP,STATUS)" > $tmp_folder/${project##*,}.csv | |
gcloud compute instances list --project "${project##*,}" '--format=json(NAME,ZONE,MACHINE_TYPE,PREEMPTIBLE,INTERNAL_IP,EXTERNAL_IP,STATUS)' | jq -r '.[] | select(.machineType | contains("custom")) | [.name, (.zone | split("/")[-1]), (.machineType | split("/")[-1]), .scheduling.preemptible, .networkInterfaces[0].networkIP, .networkInterfaces[0].accessConfigs[0].natIP, .status] | @csv' > ${tmp_folder}/${project##*,}.csv | |
if [ -e "${tmp_folder}/${project##*,}.csv" ]; then | |
if [ ! -s "${tmp_folder}/${project##*,}.csv" ]; then | |
rm -f "${tmp_folder}/${project##*,}.csv" | |
fi | |
fi | |
done | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment