{"id":5944,"library":"google-cloud-alloydb-connector","title":"Google Cloud AlloyDB Connector","description":"The `google-cloud-alloydb-connector` is a Python client library that provides a secure, encrypted proxy for connecting to Google Cloud AlloyDB instances, ensuring database traffic is protected. It abstracts away the need for explicit SSL/TLS configuration and credential management for database connections. The current version is 1.12.1, and it receives regular updates and patches, typically on a monthly or bi-monthly schedule.","status":"active","version":"1.12.1","language":"en","source_language":"en","source_url":"https://github.com/GoogleCloudPlatform/alloydb-python-connector","tags":["google-cloud","alloydb","database","connector","postgresql","security"],"install":[{"cmd":"pip install google-cloud-alloydb-connector","lang":"bash","label":"Install core connector"},{"cmd":"pip install google-cloud-alloydb-connector[psycopg2]","lang":"bash","label":"Install with psycopg2 driver (common)"},{"cmd":"pip install google-cloud-alloydb-connector[asyncpg]","lang":"bash","label":"Install with asyncpg driver (async)"}],"dependencies":[{"reason":"Required for PostgreSQL database interaction if using the psycopg2 driver. Not included by default.","package":"psycopg2-binary","optional":true},{"reason":"Required for asynchronous PostgreSQL database interaction if using the asyncpg driver. Not included by default.","package":"asyncpg","optional":true}],"imports":[{"symbol":"Connector","correct":"from google.cloud.alloydb.connector import Connector"},{"note":"Useful for specifying public or private IP connection.","symbol":"IPTypes","correct":"from google.cloud.alloydb.connector import IPTypes"}],"quickstart":{"code":"import os\nimport psycopg2\nfrom google.cloud.alloydb.connector import Connector\n\n# --- Environment Variables (Recommended for Production) ---\n# Replace with your actual AlloyDB instance connection details or set as ENV vars.\n# Ensure the service account running this code has 'AlloyDB Connection User' role.\nPROJECT_ID = os.environ.get('GOOGLE_CLOUD_PROJECT', 'your-project-id')\nREGION = os.environ.get('ALLOYDB_REGION', 'us-central1')\nCLUSTER_ID = os.environ.get('ALLOYDB_CLUSTER_ID', 'your-cluster-id')\nINSTANCE_ID = os.environ.get('ALLOYDB_INSTANCE_ID', 'your-instance-id')\nDB_USER = os.environ.get('ALLOYDB_DB_USER', 'postgres')\nDB_PASS = os.environ.get('ALLOYDB_DB_PASS', 'your-db-password') # Use Secret Manager in production\nDB_NAME = os.environ.get('ALLOYDB_DB_NAME', 'postgres')\n\n# Full instance connection name format: projects/<PROJECT>/locations/<REGION>/clusters/<CLUSTER>/instances/<INSTANCE>\nINSTANCE_CONNECTION_NAME = (\n    f\"projects/{PROJECT_ID}/locations/{REGION}/clusters/{CLUSTER_ID}/instances/{INSTANCE_ID}\"\n)\n\ndef main():\n    connector = None\n    conn = None\n    try:\n        # 1. Initialize the AlloyDB connector. It uses google.auth.default() for credentials.\n        connector = Connector()\n\n        print(f\"Attempting to connect to AlloyDB instance: {INSTANCE_CONNECTION_NAME}\")\n\n        # 2. Connect to the AlloyDB instance using psycopg2.\n        #    The connector automatically handles the secure proxy connection.\n        conn: psycopg2.Connection = connector.connect(\n            INSTANCE_CONNECTION_NAME,\n            \"psycopg2\", # Specify the database driver\n            user=DB_USER,\n            password=DB_PASS,\n            db_name=DB_NAME,\n        )\n\n        # 3. Execute a simple query to verify the connection.\n        with conn.cursor() as cursor:\n            cursor.execute(\"SELECT version();\")\n            version = cursor.fetchone()[0]\n            print(f\"Successfully connected to AlloyDB. PostgreSQL version: {version}\")\n\n    except ImportError:\n        print(\"ERROR: PostgreSQL driver 'psycopg2-binary' not found. Please install with: \")\n        print(\"       pip install google-cloud-alloydb-connector[psycopg2]\")\n    except Exception as e:\n        print(f\"An error occurred during connection: {e}\")\n        # Common errors:\n        if \"PERMISSION_DENIED\" in str(e):\n             print(\"Hint: Ensure the service account has 'AlloyDB Connection User' role.\")\n        elif \"Invalid instance connection name\" in str(e):\n             print(\"Hint: Check the format of INSTANCE_CONNECTION_NAME.\")\n    finally:\n        # 4. Clean up resources.\n        if conn:\n            conn.close()\n        if connector:\n            connector.close() # Important: close the connector to release resources\n\nif __name__ == \"__main__\":\n    main()","lang":"python","description":"This quickstart demonstrates how to establish a secure connection to a Google Cloud AlloyDB instance using `google-cloud-alloydb-connector` and the `psycopg2` driver. It assumes you have `psycopg2-binary` installed (e.g., via `pip install google-cloud-alloydb-connector[psycopg2]`). Remember to replace placeholder values or set environment variables for your project, instance, and database credentials."},"warnings":[{"fix":"Ensure you install a compatible database driver like `psycopg2-binary` (e.g., `pip install google-cloud-alloydb-connector[psycopg2]`) or `asyncpg` (`pip install google-cloud-alloydb-connector[asyncpg]`).","message":"The `google-cloud-alloydb-connector` does NOT include a database driver (e.g., `psycopg2` or `asyncpg`). You must install one separately, or use the optional `[psycopg2]` or `[asyncpg]` extras during installation.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Grant the `roles/alloydb.connectionUser` role to the principal attempting to connect. Check Cloud Logging for `PERMISSION_DENIED` errors.","message":"Connecting to AlloyDB requires appropriate IAM permissions. The service account or user identity used to run the connector must have the `AlloyDB Connection User` role on the AlloyDB instance.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Double-check that your instance connection name precisely matches the required format, including `projects/`, `locations/`, `clusters/`, and `instances/` prefixes for each part.","message":"The AlloyDB instance connection name has a specific format: `projects/<PROJECT>/locations/<REGION>/clusters/<CLUSTER>/instances/<INSTANCE>`. Incorrectly formatted names will result in connection failures.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Always include `conn.close()` and `connector.close()` in a `finally` block or use a context manager if supported by your database driver to ensure resources are properly released.","message":"It's crucial to close both the database connection (`conn.close()`) and the connector itself (`connector.close()`) when they are no longer needed. Failure to close the connector can lead to resource leaks (e.g., open sockets or threads).","severity":"gotcha","affected_versions":"All versions"},{"fix":"For asynchronous code, use `connector.connect_async()` with an `await` keyword. For synchronous code, use `connector.connect()`.","message":"The connector provides both synchronous (`connect()`) and asynchronous (`connect_async()`) methods. Ensure you use the correct method for your application's concurrency model (e.g., `await connector.connect_async()` for async applications). Mixing them incorrectly will lead to runtime errors or deadlocks.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-14T00:00:00.000Z","next_check":"2026-07-13T00:00:00.000Z"}