GCP Python get disk infromation

31 Views Asked by At

I'm trying to get disk information required for metric filter:

"filter": f'metric.type="agent.googleapis.com/disk/percent_used" AND metric.labels.state="used" AND metric.labels.device="{self.disk}" AND resource.labels.instance_id="{self.instance}"

where self.disk should be like /dev/disk but I'm not able to get this information using googleapiclient.discovery or google.cloud.compute_v1 (InstancesClient, DiskClient)

Is there any possibility to get this information?

1

There are 1 best solutions below

0
Dion V On

To retrieve the disk information needed for the metric filter, it cannot directly obtain the device paths (like dev/disk) using the Google Cloud Python libraries (googleapiclient.discovery or google.cloud.compute\_v1). However, you can still fetch the relevant details through the Compute Engine API.

You can utilize the DiskListFilter class from the google.api\_core.page\_iterator module to filter disks based on their labels. In particular, you want to find disks associated with your desired instance and then extract the corresponding names.

You may try this example as reference:

import os
from google.oauth2 import service_account
from google.cloud import compute_v1 as compute

def get_disk_names_for_instance(project_id, instance_name, scopes=[], credential_file='key.json'):
    """Get disk names for specified instance."""
    credentials = service_account.Credentials.from_service_account_info(
        _read_json_config(credential_file))

    client = compute.InstancesClient(credentials=credentials, project=project_id)
    instance_ref = client.instances_path(project_id, zone, instance_name).get()
    instance = next(iter(instance_ref.instances), None)

    disk_list_filter = compute.DiskListFilter('metadata.items[0].value').eq(instance.name)
    disks_client = compute.DisksClient(credentials=credentials, project=project_id)
    page_iterator = disks_client.list_disks(view='ADVANCED', filter=disk_list_filter)

    disk_names = []
    for response in page_iterator:
        for disk in response.disks:
            disk_names.append(disk.name)

    return disk_names


def _read_json_config(filename):
    with open(filename, 'r') as json_file:
        return json.loads(json_file.read())


if __name__ == "__main__":
    PROJECT_ID = "<your_project_id>"
    INSTANCE_NAME = "<your_instance_name>"
    DISKS_FOR_INSTANCE = get_disk_names_for_instance(PROJECT_ID, INSTANCE_NAME)
    print("\n".join(DISKS_FOR_INSTANCE))