如何使用python连接Aurora PostgreSQL无服务实例



我创建了与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?

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

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

以下是一些故障排除技巧。

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

这是AWS的官方故障排除指南。

最新更新