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

Anb*_*yan 3 postgresql amazon-s3 amazon-web-services amazon-vpc aws-lambda

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

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

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

并且还将虚拟私有云 (VPC)配置为默认云,还包括 Ec2 实例详细信息,但我无法从数据库获取连接。尝试从 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())
    }
Run Code Online (Sandbox Code Playgroud)

我用谷歌搜索了很多,但我找不到任何解决方法。有什么方法可以完成这个要求吗?