Search code examples
google-cloud-platformautomationlabelinstance

GCP: query all instances on all projects with specific label


I am looking for an automated solution in GCP to query every month ALL instances on ALL projects with a specific label; for example, "test".

I would like the result to be grouped by the project (ID or name)

Is there a way to do that?


Solution

  • Welcome!

    Your question would benefit from describing what you've tried.

    LABEL_KEY="test"
    
    PROJECTS=$(gcloud projects list --format="value(projectId)")
    
    for PROJECT in ${PROJECTS}
    do
      gcloud compute instances list \
      --project=${PROJECT} \
      --filter=labels=${LABEL_KEY} \
      --format="value(name)"
    done
    

    The problem with the above approach is that, if the Compute Engine service isn't enabled in a project, you'll be prompted to enable it (and you probably don't wish to do so).

    So, you can check each ${PROJECT} for the list of enabled services, filter by compute.googleapis.com and then, if it's not in the list, pass on that project:

    SERVICE="compute.googleapis.com"
    
    gcloud services list \
    --project=${PROJECT} \
    --filter="name.scope(services)=${SERVICE}" \
    --format="value(name)"