Google Compute Engine Guest Environment Utilities

2.8.13 · active · verified Thu Apr 16

The `google-compute-engine` library provides core utilities, scripts, and daemons that run within Google Compute Engine (GCE) virtual machine instances. It enables VMs to properly interact with the GCE platform, primarily by reading from and writing to the metadata server. This package is part of the standard Google-provided OS images for Compute Engine, and its primary role is to facilitate the VM's lifecycle and configuration, rather than acting as a client library for managing GCE resources externally. The latest PyPI version is 2.8.13, but the public releases on GitHub are quite old (late 2019), indicating an infrequent, system-level release cadence.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to programmatically retrieve VM and project metadata from within a Google Compute Engine instance using Python's `requests` library. This is the primary way applications and system scripts on a GCE VM interact with the environment, often leveraged by the underlying `google-compute-engine` guest environment components. The metadata server provides crucial information like instance name, project ID, zone, and custom metadata, which are essential for applications to adapt to their running environment. This code should be run directly on a GCE VM.

import requests
import json
import os

# This quickstart demonstrates how to access VM metadata from within a Google Compute Engine instance.
# The google-compute-engine package helps manage this interaction at a system level.

METADATA_URL = 'http://metadata.google.internal/computeMetadata/v1/'
HEADERS = {'Metadata-Flavor': 'Google'}

def get_metadata(path):
    try:
        response = requests.get(METADATA_URL + path, headers=HEADERS, timeout=1)
        response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
        return response.text
    except requests.exceptions.RequestException as e:
        # Check if running on a GCE instance or if URL is accessible
        if 'metadata.google.internal' in str(e):
            return f"Error accessing metadata. This code must run inside a Google Compute Engine VM. Details: {e}"
        else:
            return f"Error accessing metadata: {e}"

if __name__ == '__main__':
    print('--- Instance Name ---')
    instance_name = get_metadata('instance/name')
    print(f'Instance Name: {instance_name}')

    print('\n--- Project ID ---')
    project_id = get_metadata('project/project-id')
    print(f'Project ID: {project_id}')

    print('\n--- Zone ---')
    zone_full = get_metadata('instance/zone')
    zone = zone_full.split('/')[-1] if 'zones/' in zone_full else zone_full
    print(f'Zone: {zone}')

    print('\n--- Custom Metadata (example) ---')
    # To test custom metadata, add a key-value pair 'my-custom-key: my-custom-value'
    # to your VM or project metadata via gcloud CLI or Cloud Console.
    # Example: gcloud compute instances add-metadata my-instance --metadata=my-custom-key=my-custom-value --zone=us-central1-a
    custom_key = 'instance/attributes/my-custom-key'
    custom_value = get_metadata(custom_key)
    print(f'Custom Metadata (my-custom-key): {custom_value}')

    print('\n--- All Project Attributes (JSON format) ---')
    all_project_attributes_json = get_metadata('project/attributes/?recursive=true')
    try:
        print(json.dumps(json.loads(all_project_attributes_json), indent=2))
    except json.JSONDecodeError:
        print(all_project_attributes_json)

view raw JSON →