Reputation: 1941
Is there any way to get all the instances using the python google library without having to iterate through all the zones and request the instances individually?
Thank you
Upvotes: 1
Views: 890
Reputation: 361
Yes, Its possible to get all the instances using the python google library without having to iterate through all the zones.
Below are the code.
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]
Upvotes: 0
Reputation: 81336
No, you must iterate thru each of your projects and then each zone within the project. If you are only using one project, then iterate thru each zone.
This may sound unusual, but think of it this way. Each zone is a data center. You are connecting to each data center to access resources.
Upvotes: 4