3

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 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Is it possible to configure a database in an ec2 to use VPC? I didn't find samples
@Mithsew I'm not sure what you mean by "configure a database in an ec2 to use VPC". If you are running a database on an Amazon EC2 instance, that EC2 instance will be in a VPC. Therefore, the database is accessible via the VPC.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.