pythongoogle-cloud-platformgoogle-compute-enginegoogle-compute-api

How do I specify only running instances in Google's Python API client?


I am building a list of gcloud instances using the Python API.

These are the commands that pull the info from GCP on the servers:

project_id = 'company1'
zone = 'us-east1-b'
compute = googleapiclient.discovery.build('compute', 'v1')
result = compute.instances().list(project=project_id, zone=zone).execute()

When I run the script it pulls info for ALL the servers in the projects both running and stopped.

How can I specify that I only want to get the running servers using these commands? Can I specify a status=running somewhere in those commands?


Solution

  • If you refer to the API documentation for list(), notice the parameter filter=None. To filter the output, specify a filter.

    More details about filers are here.

    To filter on running instances, use the filter status=running

    result = compute.instances().list(project=project_id, zone=zone, filter='status=running').execute()