gpt4 book ai didi

postgresql - 通过 AWS-lambda 函数访问在 EC2 实例中运行的数据库

转载 作者:行者123 更新时间:2023-12-05 03:00:12 25 4
gpt4 key购买 nike

我在 python3.6 中编写了 lambda 函数来访问在 EC2 实例中运行的 postgresql 数据库。

       psycopg2.connect(user="<USER NAME>",
password="<PASSWORD>",
host="<EC2 IP Address>",
port="<PORT NUMBER>",
database="<DATABASE NAME>")

创建了具有所需依赖项的部署包作为 zip 文件并上传到 AWS lambda。为了构建依赖项,我遵循了 THIS引用指南。

并且还将 Virtual Private Cloud (VPC) 配置为默认配置,还包括 Ec2 实例详细信息,但我无法从数据库获取连接。尝试从 lambda 连接数据库时导致超时。

enter image description here

Lambda 函数:

from __future__ import print_function
import json
import ast,datetime
import psycopg2


def lambda_handler(event, context):
received_event = json.dumps(event, indent=2)
load = ast.literal_eval(received_event)

try:
connection = psycopg2.connect(user="<USER NAME>",
password="<PASSWORD>",
host="<EC2 IP Address>",
# host="localhost",
port="<PORT NUMBER>",
database="<DATABASE NAME>")

cursor = connection.cursor()
postgreSQL_select_Query = "select * from test_table limit 10"
cursor.execute(postgreSQL_select_Query)
print("Selecting rows from mobile table using cursor.fetchall")
mobile_records = cursor.fetchall()

print("Print each row and it's columns values")
for row in mobile_records:
print("Id = ", row[0], )

except (Exception,) as error :
print ("Error while fetching data from PostgreSQL", error)
finally:
#closing database connection.
if(connection):
cursor.close()
connection.close()
print("PostgreSQL connection is closed")

return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!'),
'dt' : str(datetime.datetime.now())
}

我在谷歌上搜索了很多,但我找不到解决这个问题的方法。有什么办法可以满足这个要求吗?

最佳答案

您的配置需要:

  • VPC 中的数据库
  • Lambda 函数配置为使用与数据库相同的 VPC
  • Lambda 函数的安全组 (Lambda-SG)
  • 数据库 (DB-SG) 上的安全组,允许相关数据库端口上来自 Lambda-SG 的入站连接<

DB-SG是指Lambda-SG

关于postgresql - 通过 AWS-lambda 函数访问在 EC2 实例中运行的数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57061476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com