Search code examples
python-3.xgoogle-cloud-platformgcloudgoogle-cloud-python

How to list the most compute instances' info for a project in GCP?


I am trying to list all VMs that exist under all projects associated with my account, including their OS and any other tag I can find. I have a list with the projects already so what I am using is:

 for project in project_df["project_id"]:
    subprocess.run(["gcloud config set project {}".format(project)], shell=True)
    cp = subprocess.run(["gcloud compute instances os-inventory list-instances"], shell=True)
    print(cp)

This does work, but the only labels I get are:

NAME ZONE MACHINE_TYPE PREEMPTIBLE INTERNAL_IP EXTERNAL_IP STATUS

How can I get the OS of the VMs? And possible more tags? I tried using: GET https://compute.googleapis.com/compute/v1/projects/{project}/aggregated/instances, without success since I couldn't make requests or urllib work with it.

Is there any other python library from the sdk or another gcloud command that I am missing?

Thanks


Solution

  • Based on @DazWilkin 's answer, what worked for my case was the following:

    I ran gcloud compute instances list --format=flattened that showed me many (if not all) possible labels. Then I found the ones that don't appear when you run gcloud compute instances list, and ran the following to get what I wanted:

    gcloud compute instances list --format="csv(name, zone, labels.compute_machine_type, canIpForward,  labels.os, creationTimestamp, status)" > compute_info.csv
    

    This way I also avoided using the compute API.