Last active
December 1, 2023 06:02
-
-
Save shashyajoshi/ab61f33f564ecf52a53f1f7faafd4e65 to your computer and use it in GitHub Desktop.
Script to collect instance labels and metadata
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 | |
# Header row for the CSV output | |
echo "project_id,name,labels-app-name,labels-biz-unit,labels-env-name,metadata-server-role,metadata-server-type,metadata-os-image" | |
# for every project in the list get the required details. Remove CSV header from the gcloud output. Add the project id to the beginning of each row | |
for project in $(gcloud projects list --format="value(projectId)") | |
do | |
gcloud compute instances list --format="csv[no-heading](name, labels.app-name, labels.biz-unit, labels.env-name, metadata.items.server-role, metadata.items.server-type, metadata.items.os-image)" --project $project | sed "s/^/$project,/" | |
done |
Extending on what is written above, here is the code I added to get around the projects where the Compute Engine API is not enabled. The output is just a clean list of projects and related instances.
r=$(gcloud services list --project "${project}" --format="value(NAME)" --filter="NAME:compute.googleapis.com")
if [ "$r" = "compute.googleapis.com" ]; then
gcloud compute instances list --format="csv[no-heading](name, labels.app-name, labels.biz-unit, labels.env-name, metadata.items.server-role, metadata.items.server-type, metadata.items.os-image)" --project $project | sed "s/^/$project,/"
fi
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When using this script I found there are verious projects that don't have Compute enabled, and they stop execution and prompt whether you want to enable compute for that project.
I've added the following to check whether compute is enabled for the project first. I realise this overcomplicates what was meant to be a simple demonstration but I thought it might be helpful for others:
r=$(gcloud services list --project "${project}" --format="value(NAME)" --filter="NAME:compute.googleapis.com") || echo "Error getting compute status for ${project}"
I then test whether ${r} is empty before executing the instances list command.