Roua Khenissi
Roua Khenissi

Reputation: 51

list all compute instances in a specific region gcp with python

So, I can list my instances by zones using this API. GET https://compute.googleapis.com/compute/v1/projects/{project}/zones/{zone}/instances. I want now to filter my instances by region. Any idea how can I do this (using python)?

Upvotes: 1

Views: 1932

Answers (1)

Ricco D
Ricco D

Reputation: 7277

You can use aggregated_list(), to list all your instances on your project. Filtering via region could be done on the actual code. See code below where I used regex to mimic a filter using region variable.

from typing import Dict, Iterable

from google.cloud import compute_v1
import re

def list_all_instances(
    project_id: str,
    region: str
) -> Dict[str, Iterable[compute_v1.Instance]]:

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

    agg_list = instance_client.aggregated_list(request=request)

    all_instances = {}
    print("Instances found:")
    for zone, response in agg_list:
        if response.instances:
            if re.search(f"{region}*", zone):
                all_instances[zone] = response.instances
                print(f" {zone}:")
                for instance in response.instances:
                    print(f" - {instance.name} ({instance.machine_type})")
    return all_instances

list_all_instances(project_id="your-project-id",region="us-central1") #used us-central1 for testing

NOTE: Code above is from this code. I just modified it to apply the filtering above.

Actual instances on my GCP account:

enter image description here

Result from code above (only zones with prefix us-central1 were displayed):

enter image description here

Upvotes: 3

Related Questions