Primit
Primit

Reputation: 865

"Can't connect to MySQL server in lambda

import pymysql
from botocore.vendored import requests
def lambda_handler(event,context):
      conn=pymysql.connect (host ="rootrestdatabase.cd6kbmibgfod.ap-south-1.rds.amazonaws.com", user="****" , passwd="*****",db="restawsdatabase")

i want to connect rds in lambda . but i gor error like

"errorMessage": "(2003, \"Can't connect to MySQL server on 'rootrestdatabase.cd6kbmibgfod.ap-south-1.rds.amazonaws.com' (timed out)\")",
  "errorType": "OperationalError",
  "stackTrace": [
    [

i have tried it in local machine it works fine but when i deploy code in lamba it didnt worked. also both lambda function and rds are in same region. what shoud i have to do?

Upvotes: 4

Views: 8691

Answers (3)

Piyush Pranjal
Piyush Pranjal

Reputation: 584

Adding to Vladyslav Usenko answer.

If your RDS Instance is in a private subnet and you're adding your Lambda function to the same subnet and security group.

That means now both Lambda and RDS can interact with each other without any issue.

But here you might required a VPC endpoint if you're using some other service from your lambda function.

Scenario

I am using boto3 library in my lambda function to access Glue client, you might use this library for any another service like S3.

In that situation your lambda function will timeout because your VPC (in which the lambda is present) don't have a connection between VPC and another AWS service.

So here I created an GLUE endpoint and after that my issue was fixed. In your case another service endpoint might required.

Upvotes: 0

Abhilash Purohit
Abhilash Purohit

Reputation: 29

When you are connecting Lambda to My SQL DB make sure to follow the below steps:

  1. The Execution Role which is assigned to Lambda must have Permission to EC2 Full access.
  2. Go to VPC Tab in Lambda and make sure you have VPC there. Edit and add Required VPC Connection with proper Subnets and Security Groups.

Once this is done wait for 2 minutes and start testing your Lambda. It should connect to your required DB in VPC

Upvotes: 0

Vladyslav Usenko
Vladyslav Usenko

Reputation: 2376

To communicate with RDS instances, lambda functions have to be in the same VPC - a network timeout error is a great indicator of that. However, if your RDS instance is publicly accessible, make sure the security groups, which you attached to the function, allow traffic that you need.

Upvotes: 15

Related Questions