Google Cloud AlloyDB Connector
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.
Warnings
- gotcha 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.
- gotcha 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.
- gotcha 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.
- gotcha 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).
- gotcha 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.
Install
-
pip install google-cloud-alloydb-connector -
pip install google-cloud-alloydb-connector[psycopg2] -
pip install google-cloud-alloydb-connector[asyncpg]
Imports
- Connector
from google.cloud.alloydb.connector import Connector
- IPTypes
from google.cloud.alloydb.connector import IPTypes
Quickstart
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()