[英]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.我正在使用zones.list
API ( https://cloud.google.com/compute/docs/reference/rest/v1/zones/list ) 列出我项目中的所有区域。
Every time I run this, it returns all 106 zones (which is literally the total number of possible zones).每次我运行它时,它都会返回所有 106 个区域(这实际上是可能区域的总数)。
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.例如,我的项目有 4 个区域,其中包含计算实例。 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.我需要 API 只返回这 4 个区域的名称,而不是全部 106 个。我尝试了上述 API 文档中提到的过滤器。 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.它将调用 API 并返回所有项目中的 GCE 实例列表,并对它们执行其他操作。 Zone is a mandatory input field in the instances.list
API call. Zone 是instances.list
API 调用中的必填字段。 I'm fetching the zones using the above API ( zones.list
), which returns all 106 zones every time.我正在使用上面的 API ( zones.list
) 获取区域,它每次都返回所有 106 个区域。 500+ projects and 105 zones in each project => Takes a heavy toll on the automation's efficiency.每个项目中有 500 多个项目和 105 个区域 => 严重影响自动化的效率。
Please advise.请指教。 Thanks.谢谢。
zones.list , retrieves the list of Zone resources available to the specified project. zone.list ,检索指定项目可用的区域资源列表。
You will need aggregated.list which retrieves an aggregated list of all of the instances in your project across all regions and zones.您将需要aggregated.list来检索项目中所有区域和地区的所有实例的聚合列表。 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:您可以尝试以下示例 python 代码:
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.