如何结合AlloyDB Auth Proxy使用Python PostgreSQL连接器实现IAM认证?
实现AlloyDB IAM认证结合Auth Proxy的Python方案
首先确认AlloyDB Auth Proxy已正常启动,默认会监听127.0.0.1:5432,若你自定义了端口,需记好对应端口号。以下是具体实现步骤:
步骤1:安装依赖
需要安装PostgreSQL连接器和Google Cloud IAM认证相关库:
pip install psycopg2-binary google-auth
步骤2:生成IAM认证令牌
通过Google Auth库生成针对AlloyDB的认证令牌,代码示例:
import google.auth from google.auth.transport.requests import Request def generate_iam_auth_token(): credentials, project_id = google.auth.default(scopes=["https://www.googleapis.com/auth/cloud-platform"]) if credentials.expired: credentials.refresh(Request()) return credentials.token
步骤3:通过Auth Proxy连接AlloyDB并启用IAM认证
直接指定host=127.0.0.1及对应端口,将生成的令牌作为密码传入连接参数:
import psycopg2 # 生成IAM令牌 iam_token = generate_iam_auth_token() # 替换为你的数据库名、IAM用户名(通常是Google账号邮箱或服务账号邮箱) conn_params = { "host": "127.0.0.1", "port": 5432, # 若Auth Proxy用了自定义端口,替换为对应值 "dbname": "your-database-name", "user": "your-iam-username@your-project.iam", "password": iam_token, "sslmode": "require" # 必须开启SSL } # 测试连接 conn = psycopg2.connect(**conn_params) cur = conn.cursor() cur.execute("SELECT version();") print(cur.fetchone()) cur.close() conn.close()
关键注意事项
- 确保Auth Proxy启动时未限制本地连接,默认配置允许127.0.0.1访问。
- IAM用户必须拥有
roles/alloydb.client角色,且已被授权访问目标AlloyDB实例和数据库。 - IAM令牌有效期为1小时,过期后需重新生成。
内容的提问来源于stack exchange,提问作者DavidLinares
相关产品推荐
相关产品推荐

