Registry / gcp / google-cloud-alloydb-connector

google-cloud-alloydb-connector

JSON →
library1.13.1pypypi✓ verified 84d ago

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.

pip install google-cloud-alloydb-connector
INSTALL
IMPORT
SIG · GOOGLE-CLOUD-ALLOY
G
google-cloud-alloydb-connector
gcppythonv1.13.1
Install
6.0s avg
Import
2545ms
Disk
86MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.13.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.960 runs
installs and imports cleanly · install 0.0s · import 3.144s · 84.7MB
glibc
py 3.103.960 runs
installs and imports cleanly · install 6.0s · import 1.947s · 85MB
86MB installed
● package 86MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Connector
from google.cloud.alloydb.connector import Connector
IPTypes
from google.cloud.alloydb.connector import IPTypes
Useful for specifying public or private IP connection.

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.

import os import psycopg2 from google.cloud.alloydb.connector import Connector # --- Environment Variables (Recommended for Production) --- # Replace with your actual AlloyDB instance connection details or set as ENV vars. # Ensure the service account running this code has 'AlloyDB Connection User' role. PROJECT_ID = os.environ.get('GOOGLE_CLOUD_PROJECT', 'your-project-id') REGION = os.environ.get('ALLOYDB_REGION', 'us-central1') CLUSTER_ID = os.environ.get('ALLOYDB_CLUSTER_ID', 'your-cluster-id') INSTANCE_ID = os.environ.get('ALLOYDB_INSTANCE_ID', 'your-instance-id') DB_USER = os.environ.get('ALLOYDB_DB_USER', 'postgres') DB_PASS = os.environ.get('ALLOYDB_DB_PASS', 'your-db-password') # Use Secret Manager in production DB_NAME = os.environ.get('ALLOYDB_DB_NAME', 'postgres') # Full instance connection name format: projects/<PROJECT>/locations/<REGION>/clusters/<CLUSTER>/instances/<INSTANCE> INSTANCE_CONNECTION_NAME = ( f"projects/{PROJECT_ID}/locations/{REGION}/clusters/{CLUSTER_ID}/instances/{INSTANCE_ID}" ) def main(): connector = None conn = None try: # 1. Initialize the AlloyDB connector. It uses google.auth.default() for credentials. connector = Connector() print(f"Attempting to connect to AlloyDB instance: {INSTANCE_CONNECTION_NAME}") # 2. Connect to the AlloyDB instance using psycopg2. # The connector automatically handles the secure proxy connection. conn: psycopg2.Connection = connector.connect( INSTANCE_CONNECTION_NAME, "psycopg2", # Specify the database driver user=DB_USER, password=DB_PASS, db_name=DB_NAME, ) # 3. Execute a simple query to verify the connection. with conn.cursor() as cursor: cursor.execute("SELECT version();") version = cursor.fetchone()[0] print(f"Successfully connected to AlloyDB. PostgreSQL version: {version}") except ImportError: print("ERROR: PostgreSQL driver 'psycopg2-binary' not found. Please install with: ") print(" pip install google-cloud-alloydb-connector[psycopg2]") except Exception as e: print(f"An error occurred during connection: {e}") # Common errors: if "PERMISSION_DENIED" in str(e): print("Hint: Ensure the service account has 'AlloyDB Connection User' role.") elif "Invalid instance connection name" in str(e): print("Hint: Check the format of INSTANCE_CONNECTION_NAME.") finally: # 4. Clean up resources. if conn: conn.close() if connector: connector.close() # Important: close the connector to release resources if __name__ == "__main__": main()
Debug
Known issues
gotchaThe `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.
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]`).
affects: All versions
gotchaConnecting 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.
fix
Grant the `roles/alloydb.connectionUser` role to the principal attempting to connect. Check Cloud Logging for `PERMISSION_DENIED` errors.
affects: All versions
gotchaThe AlloyDB instance connection name has a specific format: `projects/<PROJECT>/locations/<REGION>/clusters/<CLUSTER>/instances/<INSTANCE>`. Incorrectly formatted names will result in connection failures.
fix
Double-check that your instance connection name precisely matches the required format, including `projects/`, `locations/`, `clusters/`, and `instances/` prefixes for each part.
affects: All versions
gotchaIt'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).
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.
affects: All versions
gotchaThe 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.
fix
For asynchronous code, use `connector.connect_async()` with an `await` keyword. For synchronous code, use `connector.connect()`.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'google.cloud.alloydb.connector'
The `google-cloud-alloydb-connector` Python package is not installed in the current environment.
fix
pip install google-cloud-alloydb-connector
ModuleNotFoundError: No module named 'psycopg2'
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.
fix
pip install psycopg2-binary
google.api_core.exceptions.PermissionDenied: 403 Permission 'alloydb.instances.get' denied
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.
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.
google.api_core.exceptions.NotFound: 404 Requested entity was not found.
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.
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>`.
Upgrade
Version history
1.13.1latest on PyPI · released Jun 8, 2026
Audit
Dependencies
psycopg2-binaryoptionalRequired for PostgreSQL database interaction if using the psycopg2 driver. Not included by default.
asyncpgoptionalRequired for asynchronous PostgreSQL database interaction if using the asyncpg driver. Not included by default.
Agent activity
24 hits · last 30 days
node
18
OpenAI (training)
1
Resources
google-cloud-alloydb-connector — pip install google-cloud-alloydb-connector · libregistry