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
@wolfclostermann
Copy link

wolfclostermann commented Aug 9, 2019

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.

@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