【问题标题】:Access database which is running in EC2 instance through AWS-lambda function通过 AWS-lambda 函数访问在 EC2 实例中运行的数据库
【发布时间】:2019-11-25 10:32:15
【问题描述】:

我在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 参考指南。

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

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())
    }

我google了很多,但我找不到任何解决方法。有什么方法可以满足这个要求吗?

【问题讨论】:

    标签: postgresql amazon-web-services amazon-s3 aws-lambda amazon-vpc


    【解决方案1】:

    您的配置需要是:

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

    DB-SG 指的是Lambda-SG

    【讨论】:

      【解决方案2】:

      要让 lambda 连接到 VPC 内的任何资源,它需要将 ENI 设置到 VPC 的相关私有子网。您是否正确设置了 EC2 的 VPC 关联和安全组? 可以参考https://docs.aws.amazon.com/lambda/latest/dg/vpc.html

      【讨论】:

        猜你喜欢
        • 2018-04-18
        • 2020-03-14
        • 1970-01-01
        • 2012-03-14
        • 2021-01-19
        • 2017-10-10
        • 2019-06-26
        • 2022-01-15
        • 1970-01-01
        相关资源
        最近更新 更多