简体   繁体   中英

How to find GCP zones that has resources in it?

I'm using the zones.list API ( https://cloud.google.com/compute/docs/reference/rest/v1/zones/list ) to list all zones in my project.

Every time I run this, it returns all 106 zones (which is literally the total number of possible zones).

My query:

Is there a filter I can use that will only return zones that has resources in it?

For example, my project has 4 zones with compute instances in them. I need the API to only return the names of those 4 zones, instead of all 106. I tried the filters mentioned in the above API documentation. None seemed to work.

Reason for my requirement: I'm trying to build an automation using our automation engine. It will make API calls and return the list of GCE instances in all projects, and perform other actions on them. Zone is a mandatory input field in the instances.list API call. I'm fetching the zones using the above API ( zones.list ), which returns all 106 zones every time. 500+ projects and 105 zones in each project => Takes a heavy toll on the automation's efficiency.

Please advise. Thanks.

zones.list , retrieves the list of Zone resources available to the specified project.

You will need aggregated.list which retrieves an aggregated list of all of the instances in your project across all regions and zones. It will still return the list of regions and zones along with the regions and zones where the instances are deployed, you will still need to use a programming language for the filter.

You may try this sample python code below:

from google.cloud import compute_v1
import re

def list_all_instances(project_id):

    instance_client = compute_v1.InstancesClient()
    request = {
            "project" : project_id,
            }

    agg_list = instance_client.aggregated_list(request=request)

    zones_with_instance = []

    for zone, response in agg_list:
        if response.instances:
            for instance in response.instances:
                zones_with_instance.append(instance.zone)
    print(zones_with_instance)

    return zones_with_instance

list_all_instances(project_id="insert_project_id_here")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM