Python GCP从任何区域获取所有实例



有没有任何方法可以使用python-google库获取所有实例,而不必遍历所有区域并单独请求实例?

谢谢

否,您必须遍历每个项目,然后遍历项目中的每个区域。如果您只使用一个项目,则遍历每个区域。

这听起来可能很不寻常,但要这样想。每个区域都是一个数据中心。您正在连接到每个数据中心以访问资源。

是的,可以使用python-google库获取所有实例,而无需遍历所有区域。

下面是代码。

from typing import Iterable
from google.cloud import compute_v1

def list_instances(project_id: str, zone: str) -> Iterable[compute_v1.Instance]:
"""
List all instances in the given zone in the specified project.
Args:
project_id: project ID or project number of the Cloud project you want to use.
zone: name of the zone you want to use. For example: “us-west3-b”
Returns:
An iterable collection of Instance objects.
"""
instance_client = compute_v1.InstancesClient()
instance_list = instance_client.list(project=project_id, zone=zone)
print(f"Instances found in zone {zone}:")
for instance in instance_list:
print(f" - {instance.name} ({instance.machine_type})")
return instance_list

# [END compute_instances_list]

最新更新