{"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":"python","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,"search_vec":"'1.12.1':53 'abstract':35 'alloydb':3,9,27,73 'away':36 'bi':67 'bi-month':66 'client':14 'cloud':2,8,26,72 'configur':42 'connect':23,48 'connector':4,10,75 'credenti':44 'current':50 'databas':30,47,74 'encrypt':20 'ensur':29 'explicit':40 'googl':1,7,25,71 'google-cloud':70 'google-cloud-alloydb-connector':6 'instanc':28 'librari':15 'manag':45 'month':64,68 'need':38 'patch':60 'postgresql':76 'protect':33 'provid':17 'proxi':21 'python':13 'receiv':56 'regular':57 'schedul':69 'secur':19,77 'ssl/tls':41 'traffic':31 'typic':61 'updat':58 'version':51","created_at":"2026-04-14T18:35:12.772567+00:00","updated_at":"2026-04-16T18:54:31.363290+00:00","problems":[{"fix":"pip install google-cloud-alloydb-connector","cause":"The `google-cloud-alloydb-connector` Python package is not installed in the current environment.","error":"ModuleNotFoundError: No module named 'google.cloud.alloydb.connector'"},{"fix":"pip install psycopg2-binary","cause":"The database driver required by your application (e.g., `psycopg2` for PostgreSQL or `mysqlclient` for MySQL) is not installed; the AlloyDB Connector provides the secure tunnel but not the database driver itself.","error":"ModuleNotFoundError: No module named 'psycopg2'"},{"fix":"Grant the `AlloyDB Client` role (or a custom role with `alloydb.instances.get` and `alloydb.clusters.get`) to the service account or user account used for authentication.","cause":"The service account or user running the application lacks the necessary IAM permissions (e.g., `AlloyDB Client` role) to access the AlloyDB instance's metadata.","error":"google.api_core.exceptions.PermissionDenied: 403 Permission 'alloydb.instances.get' denied"},{"fix":"Verify the `instance_connection_name` against your AlloyDB instance details in the Google Cloud Console, ensuring it follows the format `projects/<PROJECT_ID>/locations/<REGION>/clusters/<CLUSTER_ID>/instances/<INSTANCE_ID>`.","cause":"The `instance_connection_name` provided to the connector is incorrect, malformed, or refers to an AlloyDB instance that does not exist in the specified project and region.","error":"google.api_core.exceptions.NotFound: 404 Requested entity was not found."}],"ecosystem":"pypi","meta_description":null,"install_score":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":"1.13.1","cli_name":"","cli_version":null,"type":"library","homepage":"https://cloud.google.com/alloydb","github":"https://github.com/GoogleCloudPlatform/alloydb-python-connector","docs":null,"changelog":"https://github.com/GoogleCloudPlatform/alloydb-python-connector/blob/main/CHANGELOG.md","pypi":"https://pypi.org/project/google-cloud-alloydb-connector/","npm":null,"openapi_spec":null,"status_page":null,"smithery":null,"categories":["gcp","database"],"base_url":null,"auth_type":null,"provenance":{"verified_status":"passing","verified_at":"2026-06-28","last_verified":"2026-06-28","next_check":"2026-07-28","install_tag":null}}