Skip to content

Instantly share code, notes, and snippets.

@shashyajoshi
Last active December 1, 2023 06:02
Show Gist options
  • Save shashyajoshi/ab61f33f564ecf52a53f1f7faafd4e65 to your computer and use it in GitHub Desktop.
Save shashyajoshi/ab61f33f564ecf52a53f1f7faafd4e65 to your computer and use it in GitHub Desktop.
Script to collect instance labels and metadata
#!/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
@cbroccoli
Copy link

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