如何使用Auth Proxy和Python连接到AlloyDB?

问题描述 投票:0回答:2

我正在尝试通过loyaldb-auth-proxy连接到谷歌云中的AlloyDB。我无法成功连接到它。我在尝试执行此操作时遇到错误。

我按照https://cloud.google.com/alloydb/docs/auth-proxy/connect#pythonhttps://github.com/GoogleCloudPlatform/alloydb-auth-proxy#example-中提到的说明进行操作调用

我在后端使用FastAPI并使用sqlalchemy。


SQLALCHEMY_DATABASE_URL = "postgresql+psycopg2://<user>:<password>@\
localhost/postgres"

engine = create_engine(SQLALCHEMY_DATABASE_URL)

SesionLocal = sessionmaker(bind=engine, autocommit=False, autoflush=True)

我使用凭据启动身份验证代理

alloydb-auth-proxy "projects/<project-id>/locations/<region>/clusters/<database-id>/instances/<instance-id>" --credentials-file "key.json"

我将地址和端口保留为默认值,即地址为

127.0.0.1
和端口
5432

代理启动

[projects/<project-id>/locations/<region>/clusters/<database-id>/instances/<instance-id>] Listening on 127.0.0.1:5432
The proxy has started successfully and is ready for new connections!

但是当我运行该应用程序时,它在控制台中出现错误 -

sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) connection to server at "localhost" (::1), port 5432 failed: Connection refused (0x0000274D/10061)
        Is the server running on that host and accepting TCP/IP connections?
connection to server at "localhost" (127.0.0.1), port 5432 failed: server closed the connection unexpectedly    
        This probably means the server terminated abnormally
        before or while processing the request.

并在代理cmd中

[projects/<project-id>/locations/<region>/clusters/<database-id>/instances/<instance-id>] failed to connect to instance: Dial error: failed to dial (instance URI = "<project-id>/<region-id>/
<database-id>/<instance-id>"): dial tcp xx.xx.xx.x:5433: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

这里发生了什么事?

python-3.x google-cloud-platform sqlalchemy google-alloydb
2个回答
5
投票

AlloyDB 目前只能选择通过私有 IP 连接到它。这意味着无论您的连接方法如何(身份验证代理、Python 连接器、直接连接等),您的本地计算机都将无法访问集群。

要进行连接,您需要从与 AlloyDB 集群相同的网络 (VPC) 内进行连接,或者您需要设置类似于堡垒实例的内容,该实例具有与 AlloyDB 集群共享网络的公共入口点。

要测试这一点,最简单的方法是在与 AlloyDB 集群相同的 VPC 上启动最小的 GCE 实例。然后通过 SSH 连接到该实例,并使用 psql 客户端确认您可以连接到 AlloyDB 实例。一旦您确认这一点,为了进行开发,您要么需要将应用程序推送到该 GCE 实例才能连接,要么在您和 GCE 实例之间建立一些连接。

有几种方法可以做到这一点,我建议尽可能锁定 GCE 实例,并从本地计算机反向 SSH 隧道到该实例。或者设置一个 VPN(云 VPN 是一种选择,但相当昂贵,因此在 GCE 实例上运行您自己的 VPN 服务也是一种选择,只是更多的开销和维护)。您还可以在堡垒实例上设置诸如 Socks5 代理之类的东西,以从那里转发到您的 AlloyDB 集群,这也可以工作。


0
投票

有一种方法可以使用 AlloyDB Auth 代理从您的计算机本地连接到 AlloyDB 实例。启动代理时必须使用 --publicip 标志。这是一个例子:

. lloydb-auth-proxy-x64 项目/PROJECT_ID/位置/REGION_ID/集群/CLUSTER_ID/实例/INSTANCE_ID --端口 5433 --public-ip

AlloyDB 代理链接: https://cloud.google.com/alloydb/docs/auth-proxy/connect

我能够运行 Python 代码来查询数据、创建表以及插入数据。问题是我没有找到使用 Python 连接器库进行连接的方法,因为在这种情况下,您应该提供 URI (projects/PROJECT_ID/locations/REGION_ID/clusters/CLUSTER_ID/instances/INSTANCE_ID),而我找不到使用IP的方式,在我们的代理方法中是127.0.0.1

这是我运行选择的Python代码:

import sqlalchemy
import psycopg2

username = 'postgres'  # DB username
password = 'accenture1'  # DB password
host = '127.0.0.1'  # Public IP address for your instance
port = '5433' #Port of you Cloud SQL instance
database = 'postgres'  # Name of database ('postgres' by default)

db_url = 'postgresql+psycopg2://{}:{}@{}:{}/{}'.format(username,
password, host, port, database)

pool = sqlalchemy.create_engine(db_url)
with pool.connect() as db_conn:
result = db_conn.execute(sqlalchemy.text("select * from public.students;")).fetchall()
   
   for row in result:
print (row)

这是插入数据的代码:

from sqlalchemy import Table, Column, Integer, String, MetaData, text
import sqlalchemy
import psycopg2

username = 'postgres'  # DB username
password = 'accenture1'  # DB password
host = '127.0.0.1'  # Public IP address for your instance
port = '5433' #Port of you Cloud SQL instance
database = 'postgres'  # Name of database ('postgres' by default)

db_url = 'postgresql+psycopg2://{}:{}@{}:{}/{}'.format(username, password, host, port, database)

engine = sqlalchemy.create_engine(db_url)
with engine.connect() as conn:
conn.execute(text("INSERT INTO students (name,lastname) VALUES (:name,:lastname)"), [{"name": "David", "lastname": "Linares"}, {"name": "Juan", "lastname": "Perez"}])
conn.commit()

希望这对您有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.