Search code examples
pythongoogle-cloud-platformgoogle-compute-engine

How to get number of compute engine instances running on Google Cloud


In Google Cloud documentation, the command line to get the list and number of instances that are running on a project in Google Cloud is given as following :

gcloud compute instances list

or

GET https://compute.googleapis.com/compute/v1/projects/{project}/zones/{zone}/instances

How can I get the equivalent function in Python using Google Cloud ?


Solution

  • There is documentation on this here: https://cloud.google.com/compute/docs/tutorials/python-guide

    In short:

    import googleapiclient.discovery
    
    project="your project"
    zone="your zone"
    
    compute = googleapiclient.discovery.build('compute', 'v1')
    instances = compute.instances().list(project=project, zone=zone).execute()
    
    for instance in instances:
        print(' - ' + instance['name'])