【问题标题】:How to connect Aurora PostgreSQL servreless instance using python?如何使用 python 连接 Aurora PostgreSQL 无服务器实例?
【发布时间】:2021-09-25 21:53:10
【问题描述】:

我创建了与 PostgreSQL 兼容的 Amazon Aurora,并且知道我想连接该数据库并插入和获取数据,但我无法使用 python 连接我的 AWS Aurora PostgreSQL...

我的代码:

def connection_maker(self):
    try:
        ENDPOINT = "assetsintel.cluster-cjeiapuahe69.us-east-1.rds.amazonaws.com"
        PORT = 5432
        USR = "postgres"
        REGION = "us-east-1"
        DBNAME = "assetsintel"
        PASS= "ScottRocks2020!*"

        # gets the credentials from .aws/credentials
        session = boto3.Session(profile_name='default')
        client = session.client('rds')
        print(f'Client: {client}')

        token = client.generate_db_auth_token(DBHostname=ENDPOINT, Port=PORT, DBUsername=USR, Region=REGION)
        print(f'Token: {token}')

        try:
            conn = psycopg2.connect(host=ENDPOINT, port=PORT, database=DBNAME, user=USR, password=token,
                                    sslmode='prefer', sslrootcert="/home/mobin/Downloads/boston_mobin_lus_.pem")
            cur = conn.cursor()
            cur.execute("""SELECT now()""")
            query_results = cur.fetchall()
            print(f'Query results: {query_results}')
        except Exception as e:
            print("Database connection failed due to {}".format(e))

        return None
    except Exception as error:
        logging.error(f'in Creating connection ! {error}')

toker 打印后卡住了:

错误:

Database connection failed due to could not connect to server: Connection timed out
    Is the server running on host "assetsintel.cluster-cjeiapuahe69.us-east-1.rds.amazonaws.com" (172.31.10.129) and accepting
    TCP/IP connections on port 5432?

【问题讨论】:

  • 您必须转到 rds 的安全组并允许来自应用程序的传入连接。你做了那部分吗?你在哪里运行 python 代码。
  • @ArunK 我在 ubuntu 上的本地机器上运行我的代码,是的,我已经完成了允许入站和出站流量...
  • 这不是python程序的问题。这是一个网络问题。这就是我为您发布答案的原因。从 rds 实例开始。检查 rds 实例是否配置为可公开访问。然后进入子网,看看子网是否有通往互联网的路由。

标签: python postgresql amazon-web-services aws-aurora-serverless


【解决方案1】:

如您所见,主机名 x.cluster-y.us-east-1.rds.amazonaws.com 正在解析为私有 IP 地址('172.31.xx.xx')。私有 IP 地址只能在其自己的网络中访问。

这里可能发生的情况是,当您创建 RDS 实例时,您必须将其创建为私有实例。因此,无法通过 Internet 访问 RDS 实例。

这里有一些解决问题的技巧。

  • RDS 实例自行配置为可公开访问
  • 确保 VPC 具有关联的互联网网关。
  • RDS 数据库子网应该有到互联网网关的路由
  • 最后,RDS 安全组应该允许来自您的家庭 IP 的流量

Here 是 AWS 官方故障排除指南。

【讨论】:

  • 好的,让我试试,写完整个脚本后,我将在 AWS 上 dockerize 并运行这个脚本,所以我必须为此做些什么...我需要添加 docker network ip.. .
  • 您可以在 EC2 实例或 Fargate 等内部运行 docker。更好的方法是转到 RDS 的安全组并允许来自 EC2 实例的安全组的流量。或者您可以允许整个子网。我上面给出的所有建议都是关于从本地计算机访问 RDS。如果入站规则允许,您已经可以在 aws VPC 中访问 RDS。
猜你喜欢
  • 2020-01-23
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 2019-06-15
  • 1970-01-01
  • 2022-06-25
  • 2019-01-13
相关资源
最近更新 更多