2
votes

I wrote the lambda function in python3.6 to access the postgresql database which is running in EC2 instance.

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

created deployment package with required dependencies as zip file and uploaded into AWS lambda.To build dependency i followed THIS reference guide.

And also configured Virtual Private Cloud (VPC) as default one and also included Ec2 instance details, but i couldn't get the connection from database. when trying to connect database from lambda result in timeout.

enter image description here

Lambda function:

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

I googled quite a lot, But i couldn't found any workaround for this.is there any way to accomplish this requirement?

2

2 Answers

2
votes

Your configuration would need to be:

  • A database in a VPC
  • The Lambda function configured to use the same VPC as the database
  • A security group on the Lambda function (Lambda-SG)
  • A security group on the Database (DB-SG) that permits inbound connects from Lambda-SG on the relevant database port

That is, DB-SG refers to Lambda-SG.

0
votes

For lambda to connect to any resources inside a VPC, it needs to setup ENIs to the related private subnets of the VPC. Have you set up the VPC association and security groups of the EC2 correctly? You can refer https://docs.aws.amazon.com/lambda/latest/dg/vpc.html